In this tutorial, we will learn how to check if a variable is a None Type. This can help you handle the errors and verify that a variable’s value is NULL.
Method 1: Using the Is Keyword
One of the most common methods to check if a variable is None or not is by using the “is” keyword. The keyword should return True if the variable is NULL and False otherwise. We can then wrap this construct inside an “if” statement as shown in the following example code:
if(var isNone):
print("yeap!, that's none")
else:
print("nope, not none")
Once we run the previous code, we see an output as shown in the following:
yeap!, that's none
From the previous output, we can see that the program returns True since the value of the variable is None.
We can also attempt the same by setting the value of var to 0.
if (var is None):
print("yeap!, that's none")
else:
print("nope, not none")
Running the previous code returns the following:
nope, not none
Hence, we can verify that 0 is not a None type in Python.
Method 2: Using the Isinstanceof
The isinstanceof method in Python allows us to check if a specific value belongs to a specific type. We can use this function to check if a variable is of a None type.
The resulting code is as follows:
print(isinstance(var, <em>type</em>(None)))
Running the previous code returns the following:
python3 python_none
True
Similarly, the code returns True indicating that the variable holds a None type.
Method 3: Using the Python Exception
We can also use a try…except block in Python to test if a variable is none. For example, if you attempt to carry out any operation on a None type, Python returns a NoneType exception.
We can use this code to our advantage. An example code is as follows:
try:
var + 10
except:
print("Cannot operate on None Value")
The previous code returns the code in the exception block as one value is a None type.
Cannot operate on None Value
Conclusion
In this article, we discussed the various methods of testing if a variable is a None type or not. Thanks for reading. Happy coding!