Search code examples
pythonwhile-loopflags

Python 3.9.6 - Trying to set flag to False. Keep getting error TypeError: '<' not supported between instances of 'str' and 'int'


In the code below I'm trying to set the 'active' flag to False. This fails. The program should stop running when age is 'quit', however continues.

I can see the error is because I'm trying to compare a string and an integer but I don't know why the program is reaching that point. Help appreciated.

active = True

while active:
    age = input('Enter age for ticket price: ')
    if age == 'quit':
        active = False
    else:
        age = int(age)

    if age < 3:
        print("You get in free!")
    elif age < 13:
        print("Your ticket is £10.")
    elif age > 13:
        print("Your ticket is £15.")

Error message - if age < 3: TypeError: '<' not supported between instances of 'str' and 'int'


Solution

  • If you want to keep the active flag, you have to avoid the line:

    if age < 3:
    

    Since age is now a string (equal to 'quit'). Try this:

    active = True
    
    while active:
        age = input('Enter age for ticket price: ')
        if age == 'quit':
            active = False
        else:
            age = int(age)
    
            if age < 3:
                print("You get in free!")
            elif age < 13:
                print("Your ticket is £10.")
            elif age > 13:
                print("Your ticket is £15.")