I am working on a simple python exercise where I ask a series of questions and get input from the user. I prompt the user with "Enter your age" and I want the program to continue rather than be corrupt if the user enters a letter value for the age rather than int because I am converting to int to figure if the age is less than 18 or greater than and if it is between specific ages. I can't convert letters to an int.
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
Use try/except.
age = input("Please enter your age: ")
try:
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
except:
print("Please enter a number")
If your int conversion fails the code will jump to except instead of crashing.
If you want the user to retry, you could write something like this instead. Be aware of the ranges you're using and negative numbers.
age = input("Please enter your age: ")
ageNum = 0
while(ageNum <= 0):
try:
ageNum = int(age)
if (ageNum) < 18 or ageNum > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
elif ...
except:
print("Please enter a valid number")
I'd use a while loop, e.g.
while int(age) != age:
input("Age must be an integer.\nPlease try again.")
And as #Barmar stated, you need to check your if statements.
Related
I am having issue with running this code. When I try to run it, it says it won't work because age is a string. How do I convert the string to an integer? I have also tried to do 18 - int(age) and that won't work either.
age = input ("How old are you? (): ")
if int(age) > 18 :
print("You're old enough to drink")
else:
print("You're not old enough to drink. Wait", + 18 - age, "more years")
age = input("How old are you? (): "))
try:
age = int(age)
if age > 18 :
print("You're old enough to drink.")
else:
print(f"You're not old enough to drink. Wait {18-age} more years.")
except:
print("You did not enter a valid age.")
Note that input("How old are you? (): ") is int(input("How old are you? (): "))
age = int(input("How old are you? (): "))
if int(age) > 18 :
print("You're old enough to drink")
else:
print("You're not old enough to drink. Wait {} more years".format(18-age))
You can add try.. except..
Like this:
age = input("How old are you? (): "))
try:
age = int(age)
if age > 18 :
print("You're old enough to drink.")
else:
print(f"You're not old enough to drink. Wait {18-age} more years.")
except ValueError:
print("Not a valid age. Please enter again")
and by the way, you can use f' strings for string format.
or use .format :
print("You're not old enough to drink. Wait {0} more years.".format(18-age))
while True:
age = input ("How old are you? ")
#Check if the input is a positive integer
if age.isdigit() >0:
break
if int(age) > 18 :
print("You're old enough to drink.")
else:
print("You're not old enough to drink. Wait",18 - int(age), "more years.")
#Remove the + in 18 because you already use comma after'Wait'
First a little about the program itself:
A conditional test begins the while loop (I have to use a conditional test to begin and end the loop, No flags and no break statements)
Asks for users age (user input)
Depending on the user input, it prints out different answers
My problem is that I want the program to end if the user input is 'quit'. The user input will besides 'quit' always be an int, because the program checks the users age.
This is my code:
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
This is the error i get when i put 'quit' as the input:
Please enter your age to see the price for a ticket. Enter 'quit' when done: quit
Traceback (most recent call last): File "while_loops.py", line 60, in <module>
age = int(age) ValueError: invalid literal for int() with base 10: 'quit'
Many thanks in advance for your time and effort! Best regards HWG.
Check for quit before you try to convert to int. Run in an infinite loop and break out of it when you read the input quit.
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
Alternative which meet added criteria
not use 'break' or a variable as a flag
Using an exception
while ageStr != "quit":
ageStr = input(prompt)
try:
age = int(ageStr)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
except ValueError:
pass
Using continue.
Note: this is bad as you specify and check for "quit" twice in the code and the control flow is overly complicated.
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
if age == "quit":
continue
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
while True:
age = input("\nPlease enter your age to see the price for a ticket. \n Enter 'quit' when done: '"
if age == 'quit':
break
# continue with the rest of your code
Just check to see if the input is 'quit', if so, break out of the infinite loop.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm going through the book Python Crash Course and ran into a little hiccup on one of the exercises. Basically it asks you to create a while loop that tells the user to input their age and it will return the price of a ticket based on their age. This is supposed to repeat until the user types 'quit'. Pretty simple, except I'm confused as to how I would go from converting the input from an integer (their age) to a string ("quit"). I get the error: "invalid literal for int() with base 10: 'quit'" whenever I try to type quit. This is what I have so far:
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
age = int(input(age_prompt))
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
if age == 'quit':
break
You would need to test if the variable was "quit" before converting to an integer (because "quit" obviously isn't a number, so Python rightly complains).
Here's how you could do it:
while True:
age = input(age_prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
except ValueError:
print("Invalid input. Please enter a valid number or 'quit'")
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
try:
age = input(age_prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
except ValueError:
if age == 'quit':
break
Check to see if it is an int. If not, check if it is 'quit'
User input is received as a string from the call to input(). In your example, you are directly converting the output of input() into an integer:
age = int(input(age_prompt))
Once you have converted the input to an integer, you can no longer compare the integer to the string "quit" as they are not directly comparable. You can process the input string before converting to an integer.
# read user input as a string
user_input = input(age_prompt)
if user_input == "quit":
quit()
elif user_input == SOME_OTHER_COMMAND:
other_command()
else:
# try to convert input into an integer
try:
age = int(user_input)
except ValueError:
print "Input '%s' is invalid!"
quit()
if age < 3:
...
Try this:
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
age = raw_input(age_prompt)
if age == 'quit':
break
else:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
you would have to use seperate variables (or exceptions - without example)
while True:
ui = input(age_prompt)
if ui == 'quit':
break
age = int(ui)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
print("Hello there")
name=input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
keeps showing me "Sorry bruh" at the end when entered 15. Why? What's wrong?
Cast your input to int:
age = int(input("Your age"))
You could add a try-except. Your condition should equally be evaluated on or not and
Either you use Python3 and you need to cast with int(input("Your age")) or you use Python2 and then you need to use raw_input to read the name: name=raw_input("What is your name?")
Ok , so you can try this code in python2.7 and it will work as you desired:
print("Hello there")
name=raw_input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
My code so far:
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
The program runs fine unless you enter 'quit' to end the loop. I understand that age = int(age) defines the user input as an integer. My question is how can I change it to to not treat 'quit' as an integer and end the loop when 'quit' is input.
If age is 'quit', you will break anyway. Therefore, you can just use if for the next one instead. As long as you do that anyway, you can make it an int after that if:
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
You should probably take care of those cases when the user types something else, however, so I would suggest the following:
while True:
age = input(prompt)
if age == 'quit':
break
elif not age.isdigit():
print("invalid input")
continue
age = int(age)
if age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
I would introduce a try/except here, actually.
The main goal of your application is to gather ages. So, wrap your input with a try/except to always get an integer. If you get a ValueError, you fall in to your exception block and check to see if you entered quit.
The application will tell the user it is quitting and break out. However, if the user did not enter quit, but some other string, you are told that the entry is invalid, and it will continue to ask the user for a valid age.
Also, just to make sure you never miss a 'quit' message that could be typed with different cases, you can always set the input to lower to always compare the same casing in your string. In other words, do age.lower when you are checking for the entry to be quit.
Here is a working demo:
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
try:
age = int(age)
except ValueError:
if age.lower() == 'quit':
print("Quitting your application")
break
else:
print("You made an invalid entry")
continue
if age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")