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

Python报错TypeError: can't multiply sequence by non-int of type 'float' 求助

问题排查与解决

原代码存在的问题

  • 类型不匹配错误:input()函数返回的是字符串类型,原代码直接用字符串Temp参与数学运算会触发类型错误;即使转为int/float,后续直接用+拼接数值和字符串也会报错
  • 拼写瑕疵:代码中"tempin"应为"temp in","Farenheit"正确拼写是"Fahrenheit"(非功能性问题,但影响可读性)

修正后的代码

city_name = input("Put a city name here: ")
temp_celsius = float(input("What's the temp in Celsius?: "))
temp_fahrenheit = (9/5 * temp_celsius) + 32
print(f"The temp in {city_name} is, in Fahrenheit, {temp_fahrenheit}")

关键修改说明

  1. 输入转数值类型:在获取温度输入时直接用float()转换为浮点型,既支持整数温度,也支持小数温度(比如23.5℃),彻底解决运算时的类型错误
  2. 字符串格式化输出:使用Python的f-string(格式化字符串)拼接内容,自动将数值类型转为字符串,避免TypeError: can only concatenate str (not "float") to str错误
  3. 优化编码规范:变量名改为小写下划线风格(符合Python编码规范),修正拼写瑕疵提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:12:06