Borislav Hadzhiev
Wed Apr 20 2022·3 min read
Photo by Jonny Gios
The Python "TypeError: unsupported operand type(s) for *: 'NoneType' and
'NoneType'" occurs when we try to use the multiplication operator with None
values. To solve the error, figure out where the variables got assigned a None
value and correct the assignment.
Here is an example of how the error occurs.
my_value_1 = None my_value_2 = None # ⛔️ TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' result = my_value_1 * my_value_2
The variables we are trying to multiply store a None
value which caused the
error.
We can't use the multiplication operator with a None
value on either side.
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(10) # ⛔️ TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' result = get_num() * get_num()
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 10 result = get_num() * get_num() print(result) # 👉️ 100
Use an if
statement if you need to check whether a variable doesn't store a
None
value before using the multiplication (*) 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 = 2 result = my_num_1 * my_num_2 print(result) # 👉️ 30
We check if the my_num_1
variable stores a None
value and if it does, we set
it to 2
.
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 = get_num(14) print(my_num_2) # 👉️ None # ⛔️ TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' 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 2 # 👈️ return fallback if condition not met my_num_1 = get_num(10) my_num_2 = get_num(14) result = my_num_1 * my_num_2 print(result) # 👉️ 4
Now the function is guaranteed to return a value regardless if the condition is met.