You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9.6设置active为False报TypeError:str和int不支持<比较

问题分析与解决方案

报错翻译

原报错信息:

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

翻译为:

if age < 3:
类型错误:不支持字符串(str)类型与整数(int)类型实例之间使用'<'比较运算符

问题根因

  • while循环的条件判断仅会在每一轮循环开始前执行,你在循环体内将active设为False后,并不会立刻中断当前轮次的剩余代码执行。
  • 当输入值为quit时,代码仅修改了active的值,仍会继续执行后续的年龄比较逻辑,此时age变量是字符串类型的quit,和整数做比较就会触发上述类型错误。

修复方案

方案1:调整代码结构,将年龄逻辑放入else分支

仅当输入内容不是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.")
        else:
            print("Your ticket is £15.")

方案2:匹配到退出指令直接终止循环

使用break关键字直接跳出当前循环,不需要依赖标志位判断,代码更简洁:

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

内容的提问来源于stack exchange,提问作者windmill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:30:02