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

Python代码报错TypeError:不支持str与int减法,该如何解决?

解决TypeError: unsupported operand type(s) for -: 'str' and 'int'错误

你的问题出在变量类型不匹配:temperatureinkelvin被赋值为字符串('please enter the temperature in kelvin'),Python不允许字符串和整数直接执行减法运算,因此抛出类型错误。

基础修正方案

把字符串赋值改成获取用户输入并转换为数值类型:

# 获取用户输入并转为浮点数(支持小数温度)
temperatureinkelvin = float(input('please enter the temperature in kelvin'))
temperatureincentigrade = temperatureinkelvin - 273
print(temperatureincentigrade)

更健壮的版本(处理无效输入)

如果用户可能输入非数字内容,添加异常处理避免崩溃:

try:
    temperatureinkelvin = float(input('please enter the temperature in kelvin'))
    temperatureincentigrade = temperatureinkelvin - 273
    print(f"Temperature in Celsius: {temperatureincentigrade}")
except ValueError:
    print("请输入有效的数字")

关键说明

  • input():读取用户输入的文本,返回字符串类型。
  • float()/int():将输入的字符串转换为数值类型,这样才能和整数273执行减法运算。
  • 异常处理:捕获用户输入非数字时的ValueError,给出友好提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:03:20