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

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

在下面的代码中,我试图将 'active' 标志设置为 False。这失败了。当年龄 'quit' 时,该程序应该停止 运行,但会继续。

我可以看到错误是因为我正在尝试比较字符串和整数,但我不知道为什么程序会到达那个点。感谢帮助。

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

错误信息 - 如果年龄 < 3: 类型错误:'str' 和 'int'

的实例之间不支持“<”

您需要在收到退出信号后打破循环,在 active=False 之后使用 continue 或简单地 break,那么您甚至不再需要 active 标志并且你可以写 while True:

它中断的原因是因为你在循环内的代码一直执行到最后,你比较'quit' < 3

如果你想保持活动标志,你必须避开这条线:

if age < 3:

因为年龄现在是一个字符串(等于 'quit')。试试这个:

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