0

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'
1
  • student_heights is a list of strings. You can't sum() them usefully until you convert them to integers. This will work but depends on error-fee input: a=sum(int(h) for h in student_heights). Commented Apr 23, 2022 at 21:01

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.