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

