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

Python for循环报错:int与str类型不支持+=运算的问题排查

问题分析与解决

错误原因

触发TypeError的核心问题是:input().split()返回的是字符串列表。比如你输入170 165 180,student_heights实际是["170", "165", "180"],每个height都是字符串类型。而total_height初始值是整数0,Python不允许直接把字符串和整数做加法运算,因此报错。

修复后的代码

只需要在循环中把height转换成整数类型即可:

student_heights = input("Input a list of student heights ").split()

total_height = 0
for height in student_heights:
  total_height += int(height)  # 将字符串转为整数再累加
print(total_height)

number_of_students = 0
for student in student_heights:
  number_of_students += 1
print(number_of_students)

代码优化(可选)

Python内置了更简洁的方法来完成求和与计数,无需手动写循环:

student_heights = input("Input a list of student heights ").split()
# 先把所有输入的字符串转为整数列表
height_list = [int(h) for h in student_heights]

total_height = sum(height_list)
number_of_students = len(height_list)

print(total_height)
print(number_of_students)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:35:27