AppDividend
Latest Code Tutorials

Python Check None: How to Check None Value in Python

0

Python does not have a Null value, but instead, it has None value. The None is a special singleton object, and there can only be one.

Python check none

To check none value in Python, use the is operator. The “is” is a built-in Python operator that checks whether both the operands refer to the same object or not.

data = None

if data is None:
    print("The data variable has None Value")
else:
    print("It does not have None value")

Output

The data variable has None Value

In this example, first, we have declared a data variable to None.

Then we have used the if statement with is operator to check if it is None or not. If it has None value, then it will execute the if statement; otherwise, it will execute the else statement.

Don’t use the == operator to check None.

Never use the ==(equality operator) to check the None value in Python because None is a falsy value. Doing variable == None is inefficient because None is a special singleton object; there can only be one.

data = None

if data == None:
    print("The data variable has None Value")
else:
    print("It does not have None value")

Output

The data variable has None Value

In this example, the double equality operator(==) returns the same output as the is operator, but in some scenarios, it will lead to a false result.

So, my recommendation is to use the is operator in Python.

That’s it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.