python - 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' 的实例之间不支持
解决方案
您需要在接收到退出信号后中断循环,无论是continue
afteractive=False
还是 simple break
,然后您甚至不再需要 active 标志,您可以编写while True:
它中断的原因是因为你在循环中的代码仍然执行到最后,你比较'quit' < 3
推荐阅读
- excel - 如何从两张纸中使用 vba vlookup 公式?
- javascript - WebSocket 关闭并出现协议错误 1002
- excel - 复制和粘贴多个条件并基于相同的值
- python-3.x - 上传到 Firestore 会丢失数字的准确性
- python - 如何禁用 discord.py 记录器?
- xamarin.forms - Xamarin.Forms 中的正确 Page.Loaded 事件
- python - Elasticsearch 父子映射和索引
- c - CS50 Luhn's Algorithm in C. 非常感谢帮助:)
- javascript - 使用 javascript 显示 Youtube 缩略图
- java - 将数组转换为数组索引到值的映射