How to Check If Variable is None in Python

The 0 and None are automatically cast to False in Python, so a different solution must be used to check if a value is not None or is 0. The data type of None in Python is NoneType.

To verify that, write this code:

print(type(None))

Output

<class 'NoneType'>

Comparisons to singleton objects like None should always be done with is or is not operators and never the equality operators.

Python check if none

  • By using is operator to check if a variable is None.
  • Using isinstance() method.
  • By using Dictionary.
  • Using try/except block.

To check if a variable is None in Python, use the is operator. With the help of the if statement, we can check whether the variable is None and if it is, then if statement executes otherwise, else will be executed.

Python code for checking None in Python

var = None
kb = 5

if(var is None):
   print("The var is None")

if(kb is not None):
   print("The kb is not None")

Output

The var is None
The kb is not None

In this example, we used is and is not operators to check whether the variable is None. The is not operator is precisely the opposite of None, and it is a kind of negative check for a variable. This is the safest and easiest way to check if a variable is None in Python.

Using Python isinstance() method

The isinstance() is a built-in Python method that checks whether an object is of a specific data type or not. For example, comparing type(None) with None assigned variable using isinstance() returns whether it is None or not.

The isinstance() method returns a boolean value which is either True or False based on the output of the checking variable.

var = None
kb = 5

print(isinstance(var, type(None)))
print(isinstance(kb, type(None)))

Output

True
False

You can see that it returns True when the variable is None and False when it is an integer.

Using a Dictionary to Check if a Variable Is None

Dictionary stores data in key-value pairs. We will check if the variable is None.

data = None
dict = {None: 'The variable is None'}
 
print(dict[data])

Output

The variable is None

This approach is not suitable compared to previous methods.

Using a try and except block

To deal with exceptions in Python, use the try…except block that may raise exceptions. For example, Python will raise the NoneType exception if the variable is None and it is being operated.

If we put the variable we suspect is None put in the try block, and if the variable is None, then the exception will be raised, which is caught in the catch block.

data = None
kb = 21

try:
   sum = data + kb
except:
   print("One variable is None")

Output

One variable is None

That’s it for this tutorial.

More posts

Check If a variable is String

Check If an Array is empty

Check if Dictionary has key

Leave a Comment