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

Python两变量相减报错:TypeError: unsupported operand type(s) for -: 'str' and 'int'

问题解决:Python字符串与整数减法报错

错误原因

报错信息:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

这是因为你通过input()获取的变量name是字符串类型,而预定义的name2是整数类型,Python不支持直接对字符串和整数执行减法运算。

解决方法

将输入的字符串转换为数值类型后再做减法,示例代码:

# 预定义整数变量
name2 = 50
# 获取输入并转换为整数
name = int(input("请输入一个数字:"))
# 执行减法运算
y = name - name2
print(y)

如果需要处理小数输入,就用float()代替int()进行转换,保证两个变量的数值类型一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:57:40