Pretty basic question, but I am trying to write a simple while loop in which I first need an input as int.
But in order to break out of said loop, I want to be able to write ‘quit’ which is a string. How do I do this?
active = True
while active:
age = int(input("Please state your age: "))
if age < 3:
print("The ticket is free.\n")
elif 3 <= age <= 12:
print("The ticket is 10 dollars.\n")
elif age > 12:
print("The ticket is 15 dollars.\n")
elif age == 'quit':
print("Quit program")
active = False
I tried putting the age in the last elif in a str(age) function, which I believed would turn input age back to a string, but it gives a value error. Any tips?
>Solution :
You need to check if age
is a string first, then check if it is an integer. You’re getting a ValueError
because you’re calling int(input())
, which causes the error when the input is not an integer. You can first check if the string is "quit"
before continuing with the program and also to prevent ValueError
‘s from occurring even if the user types something that isn’t "quit"
or an integer, wrap the rest of the code in a try ... except ...
.
active = True
while active:
age_input = input("Please state your age: ")
if age_input == 'quit':
print("Quit program")
active = False
else:
try:
age = int(age_input)
if age < 3:
print("The ticket is free.\n")
elif 3 <= age <= 12:
print("The ticket is 10 dollars.\n")
elif age > 12:
print("The ticket is 15 dollars.\n")
except ValueError:
print("Invalid input. Please enter an integer or 'quit'.\n")