How To Check If A Variable Is None In Python

If you have trouble and don’t know how to check if a variable is None in Python, don’t miss our article. We will give you some solutions for checking if a variable is none. Let’s go on now.

Check the type of any object in Python

In Python, we can check the type of any object by the following command:

type(name_of_object)

Example:

myVar = {
  "sky": "blue",
  "tree": "green",
  "sun": "yellow"
}
 
print("myVar has:", type(myVar))

Result:

myVar has: <class 'dict'>

As you can see, the type() function returns the object’s class type. You can use the type() function to check if a variable is None. For instance:

myVar = None
print("myVar has:", type(myVar))

Result:

myVar has: <class 'NoneType'>

Now, we will show you other alternative ways to check if a variable is None in Python.

Check if a variable is None in Python

Method 1: Using the “is” operator

The “Is” operator is used to check if variables point to the same object. The result returns true if variables belong to one object and false otherwise. Look at the following example:

Input:

# Declare variable myVar = None
myVar = None
 
print("myVar has:", type(myVar))
print(myVar is None)

Result:

myVar has: <class 'NoneType'>
True

Another way:

# Declare variable myVar = None
myVar = None
 
print("myVar has:", type(myVar))
print(type(myVar) is type(None))

Result:

myVar has: <class 'NoneType'>
True

Method 2: Using “==” operator

This operator compares the operands’ values of two variables. The result returns true if they are equal and false otherwise.

You can directly check the value of the variable like this:

Input:

# Declare variable myVar = None
myVar = None
 
print("myVar has:", type(myVar))
print(myVar == None)

Result:

myVar has: <class 'NoneType'>
True

 Also, you can check the value of the variables’ type.

# Declare variable myVar = None
myVar = None
 
print("myVar has:", type(myVar))
print(type(myVar) == type(None))

Result:

myVar has: <class 'NoneType'>
True

Method 3: Using the isinstance() function

The function checks if the object’s variable is an instance of a special class. The result is a boolean type

Syntax:

isinstance(variable_name, class_name)

Input:

# Declare variable myVar = None
myVar = None
 
print("myVar has:", type(myVar))
print( isinstance(myVar, type(None)))

Result:

myVar has: <class 'NoneType'>
True

Summary

Our tutorial gives you some explanations and solutions to check if a variable is None in Python. Objectively, we strongly recommend using the type() function to check the variable type as the most effective way. Hope our article is helpful for you.

Leave a Reply

Your email address will not be published. Required fields are marked *