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

咨询:PyCharm中Operand Error的成因及代码问题排查

解决类型不支持减法的TypeError错误

错误原因

input()函数默认返回字符串类型,你代码里的age是字符串,而date.today().year是整数类型,整数和字符串无法直接做减法运算,所以运行时触发了TypeError。PyCharm即时反馈没报错是因为静态检查无法预判用户输入的实际类型,只有运行时才会暴露这个问题。

错误代码

from datetime import date

name = input("What is your name?")
age = input("How old are you?")
year = date.today().year - age

print("Hello" + name + "!" + "You were born in" + str(year) + ".")

修正后的代码

把age用int()转换成整数类型即可:

from datetime import date

name = input("What is your name?")
# 将输入的年龄字符串转为整数
age = int(input("How old are you?"))
year = date.today().year - age

# 用f-string让输出更简洁易读
print(f"Hello {name}! You were born in {year}.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:22:45