Borislav Hadzhiev
Wed Apr 20 2022·3 min read
Photo by Andrew Svk
The Python "TypeError: unsupported operand type(s) for +: 'NoneType' and
'int'" occurs when we try to use the addition (+) operator with a None
value.
To solve the error, figure out where the variable got assigned a None
value
and correct the assignment.
Here is an example of how the error occurs.
my_num_1 = None my_num_2 = 15 # ⛔️ TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' result = my_num_1 + my_num_2
The variable on the left-hand side of the addition operator stores a None
value which caused the error.
None
value and correct the assignment.The most common sources of None
values are:
None
implicitly).None
.Make sure you aren't calling a function that doesn't return anything and expecting the return value to be a number.
# 👇️ this function returns None def get_num(): print(35) my_num_2 = 15 # ⛔️ TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' result = get_num() + my_num_2
The get_num
function doesn't return anything, therefore it implicitly returns
None
.
You can use a return
statement to return a value from a function.
def get_num(): return 35 my_num_2 = 15 result = get_num() + my_num_2 print(result) # 👉️ 50
Use an if
statement if you need to check whether a variable doesn't store a
None
value before using the addition (+) operator.
my_num_1 = None my_num_2 = 15 if my_num_1 is not None: result = my_num_1 + my_num_2 print(result) else: # 👇️ this runs print('variable stores a None value')
Alternatively, you can provide a default value if the variable stores None
.
my_num_1 = None my_num_2 = 15 if my_num_1 is None: my_num_1 = 35 result = my_num_1 + my_num_2 print(result) # 👉️ 50
We check if the my_num_1
variable stores a None
value and if it does, we set
it to 35
.
sort()
) that mutate the original object in place and return None
.Make sure you aren't storing the result of calling one in a variable.
Another common cause of the error is having a function that returns a value only if a condition is met.
def get_num(a): if a > 15: return a my_num_1 = get_num(10) print(my_num_1) # 👉️ None my_num_2 = 35 # ⛔️ TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' result = my_num_1 + my_num_2
The if
block in the get_num
function is only ran if the passed in number is
greater than 15
.
None
.To solve the error in this scenario, you either have to check if the function
didn't return None
or return a default value if the condition is not met.
def get_num(a): if a > 15: return a return 0 # 👈️ return fallback if condition not met my_num_1 = get_num(10) print(my_num_1) # 👉️ 0 my_num_2 = 35 result = my_num_1 + my_num_2 print(result) # 👉️ 35
Now the function is guaranteed to return a value regardless if the condition is met.