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

Python TypeError: 'int' object is not iterable求助:平均身高计算器异常

问题分析与解决

错误原因

出现 TypeError: 'int' object is not iterable 的直接原因是你尝试对整数进行循环遍历:

  • total_height 初始化为整数 0,但你写了 for height in total_height,整数无法被迭代。
  • number_of_students 同样初始化为整数 0,for student in number_of_students 也犯了相同错误。

修正方案

你需要遍历的是存储身高的列表 student_heights,而不是用来累加的整数变量。另外,统计学生数量可以直接用列表的长度 len(),比循环更简洁。

修正后的代码

student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
    student_heights[n] = int(student_heights[n])

total_height = 0
# 遍历学生身高列表,累加总身高
for height in student_heights:
    total_height += height
print(total_height)

# 直接用len()获取学生数量,无需循环
number_of_students = len(student_heights)
print(number_of_students)

avg_height = round(total_height / number_of_students)
print(avg_height)

额外优化(可选)

你还可以用Python内置的 sum() 函数和列表推导式进一步简化代码:

student_heights = input("Input a list of student heights ").split()
student_heights = [int(height) for height in student_heights]

total_height = sum(student_heights)
number_of_students = len(student_heights)
avg_height = round(total_height / number_of_students)

print(f"Total height: {total_height}")
print(f"Number of students: {number_of_students}")
print(f"Average height: {avg_height}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:15:38