Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Alexey Demidov
The Python "TypeError: 'NoneType' object cannot be interpreted as an integer"
occurs when we pass a None
value to a function that expects an integer
argument. To solve the error, track down where the None
value comes from and
pass an integer to the function.
Here is an example of how the error occurs.
# ⛔️ TypeError: 'tuple' object cannot be interpreted as an integer for i in range(None): print(i)
We passed a None
value to the range()
constructor which expects to get
called with an integer.
None
value comes from and correct the assignment.The most common source of a None
value (other than an explicit assignment) is
a function that doesn't return anything.
# 👇️ this function returns None def get_num(a, b): print(a + b) # ⛔️ TypeError: 'NoneType' object cannot be interpreted as an integer for i in range(get_num(5, 5)): print(i)
Notice that our get_num
function doesn't explicitly return a value, so it
implicitly returns None
.
The "TypeError: 'NoneType' object cannot be interpreted as an integer" occurs for multiple reasons:
None
implicitly).None
.None
.You can check if the variable doesn't store a None
value before calling the
function.
my_num = None if my_num is not None: for i in range(my_num): print(i) else: print('variable is None')
The if
block will run only if the my_num
variable does not store a None
value, otherwise the else
block runs.
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 > 100: return a result = get_num(5) print(result) # 👉️ None
The if
statement in the get_num
function is only ran if the passed in
argument is greater than 100
.
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 > 100: return a return 0 # 👈️ returns 0 if condition not met result = get_num(5) print(result) # 👉️ 0
Now the function is guaranteed to return a value regardless if the condition is met.