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

Python计算距100岁时长遇TypeError,求问题排查

问题根源:类型不匹配导致的减法错误

你遇到的TypeError其实是个很常见的新手问题——数据类型不兼容:你把用户输入的年龄转换成了字符串,而字符串和整数根本没法直接做减法运算。

仔细看这段代码:

age = str(input("How old are you: "))

input()函数本身返回的就是字符串,你额外套str()属于多此一举,但关键问题是:当你后续执行100 - age时,左边是整数100,右边是字符串类型的age,Python完全不知道该怎么对这两种类型做减法,所以直接抛出了错误。

修复方案

解决思路超简单:先把输入的年龄转换成整数类型完成计算,最后输出时按需转成字符串(或者用你原本想尝试的f-string,写法会更简洁)。

基础版本修复代码

import sys, math
# Inputs
name = input("What is your name: ")  # input本身返回字符串,无需额外str()
age = int(input("How old are you: "))  # 把输入转成整数类型
# Calculations
diff = 100 - age
year = 2020 - age + 100  # 先做整数运算,输出时再转字符串
# Output
print("Hey " + name + " you are currently " + str(age) + " years old, in " + str(diff) + " years you will be 100, in the year " + str(year))

更简洁的f-string版本(推荐)

既然你原本想尝试f-string,这个版本会让代码更清晰易读:

name = input("What is your name: ")
age = int(input("How old are you: "))
diff = 100 - age
year = 2020 - age + 100
print(f"Hey {name} you are currently {age} years old, in {diff} years you will be 100, in the year {year}")

额外小提示

如果担心用户输入非数字内容导致报错,可以加个简单的异常处理:

while True:
    try:
        age = int(input("How old are you: "))
        break
    except ValueError:
        print("请输入有效的数字哦!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:37:38