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")
Related
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.
I am new to coding in Python. I am trying to make my code so that if I enter the age a series of text will be printed. However, my code only works if i follow it line by line. For example, when i input the age 2000+ immediately nothing will happen. I need to first input an integer less than 12, followed by an integer over 2000.
print('Please input name')
if input() == 'Alice':
print('Hi, Alice.Please input age')
if int(input()) < 12:
print('You are not Alice, kiddo.')
elif int(input()) > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif int(input()) == 100:
print('You are not Alice, grannie.')
elif 12 < int(input()) < 99:
print('You are Alice!.')
var = input('Please input name ')
if var == 'Alice':
var = int(input('Hi, Alice.Please input age '))
if var < 12:
print('You are not Alice, kiddo.')
elif var > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif var == 100:
print('You are not Alice, grannie.')
elif 12 < var < 99:
print('You are Alice!.')
else:
print ("Invalid Name")
This code works because it asks one time and tries to see if some conditions are true, instead of asking each time.
Here I wrote code for your understanding purpose. Take new variable, so that no need to repeat input() method several times. Also, Age validation code keeps inside the first condition and it will be executed when the 1st condition will be true.
print('Please input name')
var = input()
if var == 'Alice':
print('Hi, Alice.Please input age')
var = input()
try:
if int(var) < 12:
print('You are not Alice, kiddo.')
elif int(var) > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif int(var) == 100:
print('You are not Alice, grannie.')
elif 12 < int(var) < 99:
print('You are Alice!.')
except Exception as ex:
print('Invalid Data: Error: ' + ex)
else:
print ("Invalid Name")
Every time you go to another branch in you if you are asking user to enter another age! Instead do the following:
age = int(input())
if age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age == 100:
print('You are not Alice, grannie.')
elif 12 < age < 99:
print('You are Alice!.')
print('Please input name')
if input() == 'Alice':
print('Hi, Alice.Please input age')
age = int(input()) # take input and assign it on a variable
if age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age == 100:
print('You are not Alice, grannie.')
elif 12 < age < 99:
print('You are Alice!.')
input is invoked every time when followed by (). So the multiple input()'s in the if elif's are not necessary.
store the result of input() like age = int(input()), then use age in the if and elif parts instead.
The input() function returns a string. Quoting the docs (emphasis mine):
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, in each if when you call input(), you have to enter a new string. Thus, you have to first enter an integer below 12.
To fix this problem, you need to store the original input in a variable. Now, as the docs say, input() returns a string. So, either you can cast (using int()) the integer in each case, by doing:
if int(age) < 12:
and storing the variable as a string.
Though, unless you do not have any specific reason to keep the age as a string, I'd recommend you to convert the string while storing the age in the variable in the first place:
age = int (input())
In this case, age will have an int.
Hopefully, this is what you are looking for:
while True:
name = input("Please ENTER your name: ")
if name == "Alice":
print("Hi Alice!")
break
print("Sorry, your name isn't correct. Please re-enter.")
age = False
while age != True:
age = int(input("Please ENTER your age: ")
age = True
if age < 12:
print("You're not Alice, kiddo.")
age = False
elif age > 2000:
print("Unlike you, Alice is not an undead, immortal vampire.")
age = False
elif age == 100:
print("You're not Alice, Granny!")
age = False
else:
print("You are Alice!")
age = True
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.
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")
Teaching myself Python out of a book and I'm stuck on this exercise:
A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.
I know how to make it work without using a loop but I am a uncertain how to make it work using a while loop. Any advice or examples would be greatly appreciated.
One way to do this would be an infinite loop. Don't forget to include a break condition, otherwise you won't be able to exit your program gracefully.
while True:
userinput = int(input())
if userinput < 0:
break
# your if logic goes here
I was able to figure it out on my own
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")
One way of doing it would be creating an infinite loop like such:
price = -1
while price == -1:
try:
age=int(raw_input('Age: '))
except ValueError:
print "Not a number, try again."
continue
if age <= 3:
price = 0
elif age > 3 and age < 12:
price = 10
else:
price = 15
print "The price will be "+str(price)+"$."
Note:
Rename raw_input() to input() if you are using Python 3.
I know this is an old question but none of the answers seemed great. So here's my solution to 7-5/ 7-6
loop = True
#while loop = true run 'while loop'
while loop:
#Print message
print ('Please enter your age.')
#receive input from user
age = raw_input()
#check if the user input "quit" if so end loop. Break ends program but should be replaceable by
#if age == 'quit':
# loop = False
#resulting the the same effect (ending loop)
if age == 'quit':
break
#Convert age input by user to int so it is recognized as a number by python
age = int(age)
#If/ elif pretty self explanatory
if age < 3:
price = 5
elif age < 12:
price = 10
elif age > 12:
price = 15
else:
print('Input not recognized')
break
#Print ticket price based on age and ask user if they need another price/inform them how to exit program
print('Your ticked price is $' + str(price) + '.')
print('\n If you would like to check the price for another person please enter their age now or type "quit" to exit')
The formatting might be a little off since it pasted oddly. I tried to explain what everything does. Also I use 2.7 instead of 3 so if you're using python 3 replace raw_input() with input()
Hopefully this answer was helpful to some on. GL with programming.
prompt = "How old are you? "
prompt += "\nEnter 'quit' when you are finished. "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free. Congratulations")
elif age < 13:
print("Your ticket is $10 dollars")
else:
print("Your ticket is $15 dollars")
prompt = "\nPlease enter 'done' when finished! "
prompt += "\nPlease enter your age:"
while True:
try:
age = input(prompt)
if age == 'done':
break
age = int(age)
if age <= 3:
print("Free ticket")
elif age in range(4, 12):
print("You must pay 10$")
elif age >= 12:
print("You must pay 15$")
except ValueError:
continue