Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Ilya Mondryk
The Python "TypeError: float() argument must be a string or a real number, not
'NoneType'" occurs when we pass a None
value to the float()
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: float() argument must be a string or a real number, not 'NoneType' result = float(example)
We are passing a None
value to the float()
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 = float(example or 0) print(result) # 👉️ 0.0
Functions that don't explicitly return a value return None
.
# 👇️ this function returns None def get_str(): print('3.14') # ⛔️ TypeError: float() argument must be a string or a real number, not 'NoneType' result = float(get_str())
You can use a return
statement to return a value from a function.
def get_str(): return '3.14' result = float(get_str()) print(result) # 👉️ 3.14
Use an if
statement if you need to check whether a variable doesn't store a
None
value before passing it to the float()
class.
example = None if example is not None: result = float(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 = float(example) print(result) # 👉️ 0.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.5) 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.5) print(my_num) # 👉️ 0
Now the function is guaranteed to return a value regardless if the condition is met.