Home > Blockchain >  what am i doing wrong to get this error using the sum function in python
what am i doing wrong to get this error using the sum function in python

Time:04-24

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

user input: 12 13 14 15

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

CodePudding user response:

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.

CodePudding user response:

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)
  • Related