Tyler Mathis Tyler Mathis - 5 months ago 53
Python Question

Adding numbers in a list gives TypeError: unsupported operand type(s) for +: 'int' and 'str'

I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:

Traceback (most recent call last):
File "Calculator.py", line 17, in <module>
addition = sum(inputs)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

My code is:

#declare variables
inputs = []
done = False

#while loop for inputting numbers
while done == False:
value = raw_input()
#escape loop if user enters done
if value == "Done":
print inputs
done = True

addition = sum(inputs)
print addition


raw_input yields strings, not numbers. sum() operates only on numbers.

You can convert each item to an int as you add it to the list: inputs.append(int(value)). If you use float rather than int then non-integer numbers will work too. In either case, this will produce an error if the user enters something that is neither Done nor an integer. You can use try/catch to deal with that, but that's probably out of the scope of this question.