PhantomDiclonius PhantomDiclonius - 3 months ago 6
Python Question

Getting error message when trying to break out of a while loop in Python

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.

Answer

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.