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
相关产品推荐
相关产品推荐

