student_heights = input("Input a list of studen heights ").split()
total_height = 0
for height in student_heights:
total_height += height
print(total_height)
number_of_students = 0
for student in student_heights:
number_of_students += 1
print(number_of_students)
我跟老师上了一门在线课程,我看不出我做错了什么。
我得到的错误是
Traceback (most recent call last):
File "main.py", line 5, in <module>
total_height += height
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
1条答案
按热度按时间irtuqstp1#
问题是
total_height
变量是一个数字,而height
变量是一个字符串,因为input()
函数返回的是一个字符串,为了将这两个变量相加,必须先用int(height)
将height
转换为整数,如下所示:或者,你可以把
student_heights
列表从map()
开始转换成一个数字列表,这可能会让你的代码更直观一些,比如: