Changing data types twice in one conditional statement (Python)

Question:

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?

Asked By: Sezen

||

Answers:

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")
Answered By: Broyojo

You could catch the ValueError exception, but why always raise an exception casting the str into int when it is not needed to raise it?
The best approach is to use isdecimal():

active = True
while active:
    age_input = input("Please state your age: ")
    if age_input == 'quit':
        print("Quit program")
        active = False
    elif age_input.isdecimal():
        age = int(age_input)
        if age < 3:
            print("The ticket is free.n")
        elif 3 <= age <= 12:
            print("The ticket is 10 dollars.n")
        else:
            print("The ticket is 15 dollars.n")
    else:
        print("Invalid input. Please enter an integer or 'quit'.n")

More info

It doesn’t seem active variable is needed. You could use while True and then use quit() or exit() when "quit" is detected. See more info

Answered By: Asi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.