This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Very new to programming! I am working through the book Python Crash Course.
Trying to create a simple program to determine ticket pricing. Taking in user input as age but ending the program when user inputs 'done'
Looks like this:
guest_age = ("Please enter your age. ")
while True:
age = input(guest_age)
age = int(age)
if age == 'done':
break
elif age < 3:
print("Your ticket is free!")
elif age <= 12:
print("Your ticket is $10!")
else:
print("Your ticket is $15!")
I am stumped on how to incorporate the done input without getting the
ValueError invalid literal for int() with base 10: 'done'
You need to first check if the input is 'done' before casting. So,
guest_age = ("Please enter your age. ")
while True:
age = input(guest_age)
if age == 'done':
break
age = int(age)
...
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I have to write a code that will execute the below while loop only if the user enters the term "Cyril".
I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.
number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("\nThat is incorrect, please restart the program and try again.\n")
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("\nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("\nYou have entered a number outside of the range, please try again.\n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("\nYou have entered a number outside of the range, please try again. \n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("\nThe average number you have entered is:", round(average_number, 0))
Change beginning of code to:
while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("\nThat is incorrect, please try again.\n")
You can try this even if I don't understand if your question is easy or if I am an idiot:
name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...
This question already has answers here:
How to optionally repeat a program in python
(3 answers)
Closed 2 years ago.
I have this code that only run once. Can anyone please help me to loop this particular code to run indefinitely?
Thanks in advance.
Here is my code:
def get_non_negative_int(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if value < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
return value
age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
If you are asking that your program should load again after positive values are given as input then you simply have to add a while loop.
while(True):
age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
this will run indefinitely.
prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active:
age = input(prompt)
age = int(age)
if age == 'quit':
active = False
elif age < 3:
print("Your ticket is $5")
elif age >= 3 and age < 12:
print("Your ticket is $10")
elif age >= 12:
print("Your ticket is $15")
This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?
I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is $5")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.
If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.
prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)
while True:
if user_input == 'quit':
break
age = int(user_input)
if age < 3:
price += 5
elif age < 12:
price += 10
else:
price += 15
print(f"Your ticket is ${price}")
user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I have tried making the input an integer but if I put a letter in I get the 'invalid literal for an int'
Please could you help.
def agecheck():
quit_menu = False
while quit_menu is False:
age = input("\nEnter your age: ")
if age >= "18":
print("You are the correct age.")
elif age < "18":
print("Get off this website.")
else:
print("Enter a correct integer.")
quit_menu = True
agecheck()
Both the input and what you're comparing it to should be integers if using operators like >= or <. Additionally, I suspect you actually want to quit the menu if the input is valid as opposed to invalid, and continue looping until the user enters an integer. You should also make your code exception safe in the event that something is entered that cannot be cast as an int. Try the following:
def agecheck():
quit_menu = False
while quit_menu == False:
try:
age = int(input("\nEnter your age: "))
if age >= 18:
print("You are the correct age.")
elif age < 18:
print("Get off this website.")
quit_menu = True
except:
print("Enter a correct integer.")
agecheck()
Here's something you can try -
def agecheck():
ans = input("\n Enter your age: ")
try:
age = int(ans)
if age >= 18:
print("You are the correct age.")
elif age < 18:
print("Get off this website.")
else:
print("Enter a correct integer.")
except ValueError:
print("That wasn't a number")
for i in range(3):
agecheck()
It runs three times, enter the inputs 4, 20, and "a", and notice the logs.
I'm trying to write code that includes the following:
1) Uses a conditional test in the while statement to stop the loop.
2) Uses an active variable to control how long the loop runs.
3) Use a break statement to exit the loop when the user enters a 'quit' value.
Here is my code:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"
Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.
You are converting the user's input to a number before checking if that input is actually a number. Go from this:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
To this:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
This will check for a request to exit before assuming that the user entered a number.
You convert age to an integer with int() so it will never equal 'quit'. Do the quit check first, then convert to integer:
age = input(prompt)
if age == 'quit':
break;
age = int(age)
...
This now checks if it's equal to a string literal first, so that in the case it is, it breaks correctly. If not, then continue on as usual.
You are casting the string "quit" to integer, and python tells you it's wrong.
This will work :
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
Just for the sake of showing something different, you can actually make use of a try/except here for catching a ValueError and in your exception block, you can check for quit and break accordingly. Furthermore, you can slightly simplify your input prompt to save a couple of lines.
You can also force the casing of quit to lowercase so that you allow it to be written in any casing and just force it to a single case and check for quit (if someone happens to write QuIt or QUIT it will still work).
while True:
age = input("What is your age?\nEnter 'quit' to exit: ")
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
except ValueError:
if age.lower() == 'quit':
break
As proposed in a comment above you should use raw_input() instead of input in order to handle the user input as a string so that you can check for the 'quit' string. If the user input is not equal to 'quit' then you can try to manage the input string as integer numbers. In case the user passes an invalid string (e.g. something like 'hgkjhfdjghd') you can handle it as an exception.
Find below a piece of code that demonstrates what I described above:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = raw_input(prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
except Exception as e:
print 'ERROR:', e
print("Please enter a valid age.")