TypeError: unsupported operand type(s) for +: 'int' and 'str'
What it means
You used an operator such as +, -, * or / on two values that cannot be combined that way. The message names the operator and the two types in order: here a number on the left and a string on the right.
1. A number stored as text
This raises the error
Broken
price = 10
tax = "2" # the quotes make this text
print(price + tax)
Output
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
The fix
Fixed
price = 10
tax = "2"
print(price + int(tax))
Output
12
int() turns the text "2" into the number 2. Values read from files, forms and input() are text until you convert them.
2. Adding up a list of strings with `sum()`
This raises the error
Broken
line = "4 8 15 16"
numbers = line.split()
print(sum(numbers))
Output
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
The fix
Fixed
line = "4 8 15 16"
numbers = [int(n) for n in line.split()]
print(sum(numbers))
Output
43
split() gives a list of strings. sum() starts from 0 and adds each item, so every item must be a number first.
3. A function that prints instead of returning
This raises the error
Broken
def add(a, b):
print(a + b)
total = add(2, 3) + 10
print(total)
Output
5 Traceback (most recent call last): File "<exec>", line 4, in <module> TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
The fix
Fixed
def add(a, b):
return a + b
total = add(2, 3) + 10
print(total)
Output
15
print() only shows a value. return hands it back to the caller. Without return the function gives None, and the message says 'NoneType' and 'int'.
When you see this error, check
- Read the two types in the message: they tell you which side to convert.
- Convert text to numbers with
int()orfloat()before doing math. - Print
type(x)for each value on the failing line. - If one of the types is
NoneType, a function is missing itsreturn.
Related errors
All Python errors · How to read a traceback · Step through your code