float() argument must be string or real number, not NoneType

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Ilya Mondryk

float() argument must be string or real number, not NoneType #

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.

float argument must be a string or real number not nonetype

Here is an example of how the error occurs.

main.py
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:

  1. Having a function that doesn't return anything (returns None implicitly).
  2. Explicitly setting a variable to None.
  3. Assigning a variable to the result of calling a built-in function that doesn't return anything.
  4. Having a function that only returns a value if certain condition is met.

One way to solve the error is to provide a fallback value, e.g. 0 if the variable stores None.

main.py
example = None result = float(example or 0) print(result) # 👉️ 0.0

Functions that don't explicitly return a value return None.

main.py
# 👇️ 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.

main.py
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.

main.py
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.

main.py
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.

main.py
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.

In all other cases, the function doesn't return anything and ends up implicitly returning 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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.