Exploring Python NoneType: No Value? No Problem

One of the data types provided by Python is the NoneType which you might have found when coding in Python if you have seen the keyword None.

NoneType is a Python data type that shows that an object has no value. None is the only object of type NoneType and you can use it to show that a variable has no value. None can also be used when a function doesn’t return a value or for defining an optional parameter in a function.

Are you ready to learn how to use None in this tutorial?

What Is NoneType in Python?

The NoneType in Python is a data type that represents the absence of a value or a null value. The None object is the only Python object of type NoneType.

Using the type() function in the Python shell we can see that None is of type NoneType.

>>> type(None)
<class 'NoneType'>

Now try to assign the value None to a variable. You will see that the type of that variable is also NoneType.

>>> x = None
>>> type(x)
<class 'NoneType'>

How to Check For NoneType in Python?

How can you check if a Python object is of type NoneType or, in other words, if the value of the object is equal to None?

To verify if a Python object is equal to None you can use Python’s “is operator”. You can also apply its negation using the “is not operator”.

For example, let’s take a variable called number and assign the value None to it.

Then use an if / else statement and the is operator to check if the value of this variable is None or not.

>>> number = None
>>> 
>>> if number is None:
...     print("The variable number is equal to None")
... else:
...     print("The variable number is not equal to None")
... 
The variable number is equal to None

Using the is operator we have correctly detected that the value of the variable number is None.

But, how does this work exactly?

To understand that we will simply check the value returned by the expression that uses the is operator.

>>> number is None
True

The expression using the is operator returns a boolean with the value True meaning that the variable number is equal to None.

Now, assign a value to the variable number and execute the expression again.

>>> number = 10
>>> number is None
False

This time we get back False because the variable is not equal to None.

We can also reverse the logic of the expression using the “is not” Python operator.

>>> number is not None
True

As expected, in this case, the result is a boolean with the value True.

Is None the Same as Undefined in Python?

If it is the first time you have learned about None in Python, you might think that None and undefined are the same thing in Python.

This is not the case…

By default a variable is undefined and its value becomes None only if you assign this value to it or if the variable is returned by a function that returns None.

Let’s see this in practice:

>>> print(result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'result' is not defined

We have printed the value of the variable result without assigning a value to it. That’s why we get back an error message that says that this variable is not defined.

If you try to access a Python variable before assigning a value to it the Python interpreter throws a NameError exception because the variable you are trying to access is undefined.

Now let’s assign the value None to the variable result.

>>> result = None
>>> print(result)
None

This time we don’t get an error back when we print the value of the variable result. We get back the value None.

This shows that None and undefined are not the same thing in Python.

Can a Python Function Return None?

A Python function can return None and this usually happens if the function doesn’t have a return statement or a return value. An example of a function that returns None is the print() function.

>>> print(print("Hello"))
Hello
None

The first “Hello” message is the output of the inner print() function. The None value is the output of the outer print() function that prints the value returned by the inner print() function.

To make sure this concept is clear, let’s define a custom Python function that doesn’t return any value.

First of all, we define a function called custom that returns the integer 1.

>>> def custom():
...     x = 1
...     return x
... 
>>> print(custom())
1

You can see that when we print the value returned by the function we get back the integer one.

Now update the function by removing the return statement, then print the output of the function again.

>>> def custom():
...     x = 1
... 
>>> print(custom())
None

The value returned by the function is None because the function doesn’t have a return statement.

Now, try to add the return statement without returning any value.

>>> def custom():
...     x = 1
...     return
... 
>>> print(custom())
None

Even in this case, the value returned by the function is None because even if the return statement is present that statement doesn’t return any value.

None as Default Value For Optional Parameters

In Python, None is often used as the default value for optional parameters in a function. Passing different values for optional parameters allows customization of the function’s behavior.

To explain how you can use None with an optional parameter let’s create a function that prints a simple message.

def say_hello():
    print("Hello user!")

Let’s call the function and confirm it works fine:

say_hello()

[output]
Hello user!

Now, let’s add the parameter name to the function. We will make this parameter optional.

To make the parameter of a Python function optional you can assign the value None to it in the function signature.

def say_hello(name=None):
    if name is None:
        print(f"Hello user!")
    else:
        print(f"Hello {name}!")

You can see that in the implementation of the function we are using the is operator to check if the optional parameter name is equal to None or not. Depending on that we execute one of the two print statements.

# Without passing the optional argument
say_hello()

# Passing the optional argument
say_hello('CodeFatherTech')

[output]
Hello user!
Hello CodeFatherTech!

How Do You Set a Variable to null in Python?

In other programming languages, a variable that doesn’t refer to any object is represented with the value null.

Let’s see if the value null applies to Python.

>>> number = null
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'null' is not defined

When we try to assign the value null to a variable we get back a NameError because the name “null” is not defined in Python.

The value null is not applicable to the Python programming language. To represent the concept of null you can use the value None.

Is None the Same as Zero or Empty String in Python?

None in Python is not the same as 0, is not the same as an empty string, and is not the same as a boolean with the value False. None is a specific value that represents null objects and variables.

How to Fix Python TypeError: NoneType object is not iterable

Are you executing a Python program and are you getting the following error?

TypeError: 'NoneType' object is not iterable

How can you solve this error in Python?

This error is caused by the fact that you are trying to iterate over an object that has a value equal to None.

For example, imagine you are using a for loop to go through the elements of a Python list but the value of the list, for some reason, is None.

>>> numbers = None
>>> for number in numbers:
...     print(number)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

We have set the value of the list numbers to None. Then while iterating through the list using a for loop the Python interpreter throws the error “TypeError: ‘NoneType’ object is not iterable”.

Once again, this TypeError in Python occurs because the list we are iterating through is equal to None and hence it’s not an iterable object.

In this case, the root cause of the problem is obvious because we have assigned None explicitly to the numbers variable.

In the normal execution of a program, it might be a bit more difficult to understand why the variable you are iterating through is equal to None considering that its value might be the result of another function called by your Python code.

Conclusion

Now you should have an understanding of what None is in Python and how you can use it in your programs.

You have seen that None is of type NoneType, that you can assign it to a variable, and that you can use it as a return value in a function and also to set optional function parameters.

Related article: in this tutorial, we have briefly discussed custom Python functions. Read the CodeFatherTech tutorial that will teach you how to create your Python functions.

Leave a Comment