Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: int() argument must be a string, a bytes-like object or
a real number, not 'NoneType'" occurs when we pass a None
value to the int()
class. To solve the error, correct the assignment or provide a fallback value.
Here is an example of how the error occurs.
example = None # ⛔️ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' result = int(example)
We are passing a None
value to the int()
class which causes the error.
The most common sources of None
values are:
None
implicitly).None
.One way to solve the error is to provide a fallback value, e.g. 0
if the
variable stores None
.
example = None result = int(example or 0) print(result) # 👉️ 0
Functions that don't explicitly return a value return None
.
# 👇️ this function returns None def get_str(): print('100') # ⛔️ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' result = int(get_str())
You can use a return
statement to return a value from a function.
def get_str(): return '100' result = int(get_str()) print(result) # 👉️ 100
Use an if
statement if you need to check whether a variable doesn't store a
None
value before passing it to the int()
class.
example = None if example is not None: result = int(example) print(result) else: # 👇️ this runs print('variable stores a None value')
Alternatively, you can reassign the variable to a fallback value.
example = None if example is None: example = 0 result = int(example) print(result) # 👉️ 0
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 = get_num(10) print(my_num) # 👉️ None
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, 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 = get_num(10) print(my_num) # 👉️ 0
Now the function is guaranteed to return a value regardless if the condition is met.