HWG
HWG

Reputation: 13

How to use a conditional test to exit a while loop?

First a little about the program itself:

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.

Upvotes: 0

Views: 1096

Answers (2)

Paul Rooney
Paul Rooney

Reputation: 21609

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")

Upvotes: 3

Harrison
Harrison

Reputation: 5376

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.

Upvotes: 2

Related Questions