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

如何解决Python中字符串与整数比较的TypeError错误?

解决TypeError: '<' not supported between instances of 'str' and 'int'的问题

问题根源很明确:Python的input()函数会把用户输入的内容默认转为字符串类型,你直接拿这个字符串和整数18做大小比较,类型不兼容就会触发报错。

修复方案

把输入的年龄转换成整数类型即可,修改age = input()这一行:

age = int(input())

修复后的完整代码

print("what is your name")
MyName = input()
print('nice to meet you, ' + MyName)
print('what is your age, ' + MyName)
age = int(input())
if age < 18:
    print("teenager")

进阶优化(可选)

如果担心用户输入非数字内容导致程序崩溃,可以加一层异常处理:

print("what is your name")
MyName = input()
print('nice to meet you, ' + MyName)
print('what is your age, ' + MyName)
try:
    age = int(input())
    print("teenager" if age < 18 else "adult")
except ValueError:
    print("请输入有效的数字年龄")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:51:02