Python

Python Is Not None

In Python, a None is a special keyword that tells the Python interpreter that the variable is NULL or not available. Keep in mind that a NULL value does not mean zero.

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:

var =None
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:

python3 python_none

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.

var = 0

if (var is None):

print("yeap!, that's none")

else:

print("nope, not none")

Running the previous code returns the following:

python3 python_none

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:

var = None

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:

var = None

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.

python3 python_none

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!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list