首页 > 解决方案 > Python 3.9.6 - 试图将标志设置为 False。不断收到错误 TypeError: '<' 在 'str' 和 'int' 的实例之间不支持

问题描述

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

我可以看到错误是因为我试图比较一个字符串和一个整数,但我不知道为什么程序会达到那个点。帮助表示赞赏。

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: TypeError: '<' 在 'str' 和 'int' 的实例之间不支持

标签: pythonwhile-loopflags

解决方案


您需要在接收到退出信号后中断循环,无论是continueafteractive=False还是 simple break,然后您甚至不再需要 active 标志,您可以编写while True:

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


推荐阅读