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

Python运行if/elif代码报str与int无法比较的TypeError如何解决

报错原因

你碰到的TypeError: '<' not supported between instances of 'str' and 'int'是类型不匹配错误:Python内置的input()函数不管你输入什么内容,返回值默认都是字符串类型,你直接把字符串类型的age和整数做大小比较,就会触发这个报错。

除了这个核心错误,你的代码还有几处语法问题会导致运行失败:

  • if/elif 语句行末尾必须加英文半角冒号:
  • 判断名字是否存在于名字列表里,不能写name == [],要使用in关键字做成员判断
  • Python靠缩进区分代码块,if/elif下属的执行语句必须统一缩进(一般用4个空格)
  • 年龄输入的提示语有拼写错误,you应该改成your
修正后的代码
# 这里替换成你自己存2800个名字的列表
name_list = ["Alice", "Bob", "Charlie"]

print('Enter a name')
name = input()
print('What is your age?')
# 把输入的年龄转成整数类型
age = int(input())

if name in name_list:
    print('Hi ' + name )
elif age < 12:
    print('You are not allowed here kiddo.')
elif age > 2000:
    print('Unlike you I am not an undead, immortal vampire.')
elif age > 100:
    print('You are not allowed here boomer, please leave.')

补充提示:如果用户输入年龄的时候输了非数字内容,int()转换会抛错,后续你学异常处理的时候可以给这部分加容错逻辑,初学阶段先保证输入是纯数字就能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 22:42:28