Validating user input Python [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
i am new to Python, and i was wondering if i could get some help with a script. I am trying to validate user input with this script. I would like to restrict the user input to only integers for the number of minutes including and between 1 and 10080. I am still learning all of the terminology, but Here is what i have so far. It looks like something keeps getting stuck at while True:, but i can't seem to figure out what. Any help would be greatly appreciated.
Min=int(input("Please enter the amount of minutes used as an integer ")
while True:
try:
Min = int(input('Min'))
if Min < 1 or Min > 10080:
raise ValueError
break
except ValueError:
print("Invalid number of minutes. Please try again. ")

If you fix the syntax error on the first line (missing )) it should work, but it still asks for user input twice. Removing the first line and doing some minor cleanup, we can get:
while True:
try:
minimum = int(input("Enter number of minutes: "))
if minimum < 1 or minimum > 10_080:
raise ValueError
break
except ValueError:
print("Invalid number of minutes. Please enter a value between 1 and 10,080.")

I agree with #MatthewProSkills solution, but his version doesn't account for exceptions. Other answers don't save the variable. Here's an improved version.
minimum = 0
while minimum < 1 or minimum > 10080:
try:
minimum = int(input("Please enter the amount of minutes used as an integer "))
except Exception:
print("Invalid number of minutes. Please try again. ")

Related

Variable assigned but never used? (python) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 days ago.
Improve this question
`Hello!
I am coding using python and the app I use to code is replit. It gives me a yellow error "local variable 'Age' is assigned to but never used" I have a picture if that explains better. I do not understand why it is saying that. Can someone please help me? Thank you in advance!
Link to Code: https://replit.com/join/nhojkopfys-seungmint
Image 1
Image 2
Honeslty I have changed about everything and I do not know what I am doing wrong. I have fixed my indents and rewrote this multiple times. This is a DIY lab for my class. I have read through the notes, powerpoints, textbook, and have re-coded this multiple times. I do not have a tutor and one of my classmates recommnded this platform.
This is what the code is suppossed to diplay:
//Input
Enter your guess for age: 32
Enter your guess for weight: 119
Enter your guess for birth month: April
//Output
Congratulations, the birth month is April.
Sample 3:
//Input
Enter your guess for age: 58
Enter your guess for weight: 128
Enter your guess for birth month: January
//Output
Congratulations, the weight is 128 or more.
getAge, getMonth and getWeight are functions. If you want to call them, you need to add brackets, like getAge().
So in main(), in checkYes, add brackets to all three arguments
Variables in python have scope. In this case your age, month and weight variables are locally scoped to the function getYes. They dont exist outside it. So you declare them in the function then never use them, then they go out of scope. So it correctly is telling you that you are defining these but not using them.
def getYes():
Age = getAge()
month = getMonth()
weight= getWeight()

Can someone help me understand this. It's for my python class #python

Can someone explain to me, in plain english whats going on in this line
hourly_wage = int(input('Enter hourly wage: '))
From what I understand integers allow you to multiply,add and divide. If I were to say fruit = apples + 10
and I didn't have an integer function to call that out there would be an error.
I am just trying to grasp the next step of that. I may be wrong in the above explanation, if I am please correct me. Thank you for your help.
in Python, all input is returned as a string.
input('Enter hourly wage: '))
this is just accepting the user input. so if the user were to enter the number 100 and you were to print out its type, Python would return string.
int(input('Enter hourly wage: '))
this is doing the same as above but it's forcing the input to be an integer instead.
hourly_wage = int(input('Enter hourly wage: '))
now we take the integer value and store it in hourly_wage
My Python understanding is minimal, but from what I can understand that line is simply defining that an input from the user in the "Enter hourly wage" field of some application, etc is an integer and that it equals hourly_wage. Another way to say that is hourly_wage = the integer the user typed
If anyone has further/better knowledge of this please do correct me.

How can I take a value from a document and add another value to it? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a Python program I'm writing that I would like to have track statistics given inputs. I'd like it to have two documents set up, and be able to refer to each. In each, there would be a value, let's say it's x. The program would be able to generate a number, and I'd like to be able to update the number in a given document by adding the generated number. Right now, my code would be as follows:
f1 = open("player1records.txt", "a+")
f1.write(str(int(P1wins) + int(f1.read)))
This, however, raises the following:
TypeError: int() argument must be a string, a bytes-like object or a number,
not 'builtin_function_or_method'
How can I take that x and add another number to it, then update the document?
don't forget to add the () to the end of a function to call it:
f1.write(str(int(P1wins) + int(f1.read()))) # not f1.read
this sort of thing is difficult to do safely, one tends to end up with code that does:
from os import replace
def updateRecords(value, filename="player1records.txt"):
try:
with open(filename) as fd:
prev = int(fd.read())
except (FileNotFoundError, ValueError):
prev = 0
changed = prev + value
# write to a temp file in case of failure while doing this
tmpname = filename + '~'
with open(tmpname, 'w') as fd:
fd.write(str(changed))
# perform atomic rename so we don't end up with a half written file
replace(tmpname, filename)
all of this fiddling is why people tend to end up hiding this complexity behind a relational database. Python includes a relatively nice SQLite interface. if everything was set up, you'd be able to do:
with dbcon:
dbcon.execute(
"UPDATE player SET wins=wins + ? WHERE player_id = ?",
(P1wins, 1))
and have the SQLite library take care of platform specific fiddly bits…

finding friends' birthdays in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have found help with starting an assignment that I previously did not know how to begin. I currently need to figure out a way to compare several birthdays with the current date, as prompted by the user, with the last day of a month as prompted by the user. I know there is a date timemodule that can tell the current date but I am unsure of how to use the module to work with what the user inputs...if that makes sense.
For example: If the user inputs 11/27/18 as the current date and June as the comparison month (my professor requires a month be entered instead of a date), I need to compare the birthdays from an opened file with 11/27/18 and 06/30/19 and print however many of those dates occur before July 1st, 2019 (it needs to be printed in words, my professor requires specific formatting).
I know how to format the dates that are input in my program, but I am unsure how to compare the dates from the file with what is input for comparison as it could be different every time. Currently what I have now is the inputs of strings where the user would prompt the current date and the month and I have the file opened.
your program would look something like this its not exactly what your criteria is but this is a step in the right direction. This is just one way to do it so someone might have a better program.
FriendList=[" name 1", "name 2"]
PhoneList=[ " 123" , "456"]
Birthday=["January" , "February"]
print(Birthday)
Date=input(" please choose a month or press q to exit")
# in lists the first string or number in each list will be together
# example: if janurary is chosen then name 1 and 123 will appear
while Date != 'q': # runs until q is pressed to quit
for i in range (2):# loop goes through the 2 names in the list
if Birthday[i] == Date: # compares the list of names to the date
print(FriendList[i],"" , Date[i], "" ,PhoneList[i])
Date=input(" please choose a month or press q to exit")
First you need to check the dates, start by figuring out this part: "birthday between the current date and the last day of a month "
Once you have that working, loop through the friends, and if they meet the condition then add them to a new list.
Sort the new list by alphabetical order, and print it.
This should give you an idea of where to start, once you've some code you can post that and ask for help for specific problems, but nobody will do your final for you (that's cheating!)

Errors running python code, attribute error for datetime and strptime type error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I was given a project to complete:
Help determine how much time someone has left to meet a deadline
Ask a user to enter the deadline for their project
Tell them how many days they have to complete the project
For extra credit, give them the answer as a combination of weeks & days (Hint: you will need some of the math functions from the module
on numeric values)
Now here is where I come up against a brick wall:
I have on my laptop python 2.7.12 while the tutor is using Microsoft Visual Studio 2013 and teaching cpython.
when I run my code it compiles but as soon as I input userdata it gives me the error displayed below.
MY CODE:
import datetime
currentday=datetime.date.today()
#set variable to recieve deadline for project
deadLine = 0
deadLine = raw_input('when is the deadline for your project? (dd/mm/YYYY) ')
deadLine=datetime.dateime.strptime(deadLine, '%d/%m/%Y').date()
daysLeft= deadLine-currentday
print 'Number of days left for your project is : '
print daysLeft
ERROR GIVEN:
when is the deadline for your project? (dd/mm/YYYY) 21/10/2016
Traceback (most recent call last):
File "C:\Users\Oluwaseun Okungbowa\Desktop\Video editing and python programming\projectdeadline.py", line 7, in <module>
deadLine=datetime.dateime.strptime(deadLine, '%d/%m/%Y').date()
AttributeError: 'module' object has no attribute 'dateime'
when I tried to run the tutors code, I came up with another error (again these errors are given after accepting input from user.
TUTORS CODE:
#import the datetime class
import datetime
#declare and initialize variables
strDeadline = ""
totalNbrDays = 0
nbrWeeks = 0
nbrDays = 0
#Get Today's date
currentDate = datetime.date.today()
#Ask the user for the date of their deadline
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")
deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()
#Calculate number of days between the two dates
totalNbrDays = deadline - currentDate
#For extra credit calculate results in weeks & days
nbrWeeks = totalNbrDays.days / 7
#The modulo will return the remainder of the division
#which will tell us how many days are left
nbrDays = totalNbrDays.days%7
#display the result to the user
print("You have %d weeks" %nbrWeeks + " and %d days " %nbrDays + "until your deadline.")
ERROR GIVEN:
Please enter the date of your deadline (mm/dd/yyyy): 10/21/2016
Traceback (most recent call last):
File "C:\Users\Oluwaseun Okungbowa\Desktop\Video editing and python programming\projectdeadlineteachers.py", line 16, in <module>
deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()
TypeError: strptime() argument 1 must be string, not int
Please help me understand why I am getting both errors when I run the two programs and what I must do to correct it.
Install python3 so that you and your tutor are on the same page.
However, if you do decide to stick with python 2.7, this will fix your problem.
Your problem is in this line
#Ask the user for the date of their deadline
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")
Here's an example of what I mean
>>> input()
5
5
>>> input()
10/2
5
>>> input()
10/2/2016
0
python is thinking that your date is arithmetic division of integers. change input() to raw_input() to accept the string.
i.e.
strDeadline = raw_input("Please enter the date of your deadline (mm/dd/yyyy): ")
The first error is spelling mistake( datetime not dateime, check yourself, try not to ask stackoverflow for simple things).
Second Error:
Refer to this:
about datetime.strptime()
First argument of strptime should be string ( this is what error is saying, errors help you learn better)
so make the first argument
the input was
str(deadLine)#converting deadLine to string
Edit:
I had neglected the logical error, because of which strDeadLine was an int.
The problem arrives because IDLE performs the operation( division in this case before providing it to the code). This will not be the case when using Shell, or cmd. I stand with what I said before, the best way to learn is not stack overflow but to try by yourself.
Thanks martijn-pieters for the comment.

Categories