简体   繁体   中英

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.

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 (eg 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.") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM