Python报错TypeError: can only concatenate str (not 'int') to str排查
问题分析与修复方案
核心错误原因
- 输入未转换为数值类型:
input()函数返回的是字符串(str)类型,直接将其与整数(如105、19)进行运算时,Python会抛出类型错误——字符串和整数无法直接进行算术运算或拼接。 - 错误使用
sum()函数:sum()的作用是对列表、元组这类可迭代对象求和,并非用于单个数值的计算。代码中用sum()包裹单个表达式完全多余,还会引发不必要的错误。
修复后的代码
print('Hello there! Today we will be learning how to calculate your macros! ') print(' We will start off by gathering some of your info valuable in the calculations.') # 将输入转换为数值类型,float兼容整数和小数输入 H = float(input('How tall are you in inches over the 5ft mark? ')) W = float(input('Now how much do you currently weigh in pounds? ')) A = float(input('Now how many hours of activity would you say that you get per day? ')) # 移除多余的sum(),直接执行数值运算 c = (H + 105) * 10 + 400 d = c / 4 carbs = (d * 2) / 4 # 打印计算结果 print(f"Your calculated carbs intake: {carbs}")
补充说明
- 如果确定输入都是整数,可将
float()替换为int(),但float()能兼容带小数的输入,适用性更广。 - 原代码中有一处拼写小错误:
weight应为weigh,已在修复代码中修正,不影响运行但建议规范拼写。
内容的提问来源于stack exchange,提问作者Stoic Coder
相关产品推荐
相关产品推荐

