Prince Ampong
Prince Ampong

Reputation: 9

Getting TypeError when using the sum function in Python

What am I doing wrong to get this error using the sum function in Python:

student_heights =input("Input a list of student heights ").split()
a=sum(student_heights)
print(a)

User input: 12 13 14 15

Error:

Traceback (most recent call last)
File "main.py", line 2, in <module>
TypeError unsupported operand type(s) for +:'int' and 'str'

Upvotes: 0

Views: 91

Answers (2)

idanz
idanz

Reputation: 877

The elements in your list are strings (that's how they return from input() from the console). You can, for example, convert them to integers:

a = sum(int(element) for element in student_heights)

Then you can sum them.

Upvotes: 2

debugger
debugger

Reputation: 1736

your variable student_heights is a type of list. A list accept string values. So we need to iterate through the list.

student_heights = input("Input a list of student heights ").split()
a = sum(int(i) for i in student_heights)
print(a)

Upvotes: 0

Related Questions