Reputation: 19
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)
Im following with the teacher on a online course and I don't see what im doing wrong.
the error I am getting is
Traceback (most recent call last):
File "main.py", line 5, in <module>
total_height += height
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Upvotes: 0
Views: 61
Reputation: 11090
The issue is that your total_height
variable is a number, but your height
variable is a string, because the input()
function returns a string. In order to add these two variables, you must first convert height
to a integer with int(height)
. Like this:
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)
Alternatively, you can convert the student_heights
list into a list of numbers from the beginning with map()
. This might make your code a bit more intuitive. Like this:
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)
Upvotes: 1