循环的Python帮助

xdnvmnnf  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(102)
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'
irtuqstp

irtuqstp1#

问题是total_height变量是一个数字,而height变量是一个字符串,因为input()函数返回的是一个字符串,为了将这两个变量相加,必须先用int(height)height转换为整数,如下所示:

student_heights = input("Input a list of studen 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)

或者,你可以把student_heights列表从map()开始转换成一个数字列表,这可能会让你的代码更直观一些,比如:

student_heights = map(int, 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)

相关问题