Table of Contents
This article demonstrates the different ways available to check if a variable is NULL
in Python.
What is the NULL
keyword?
The NULL
keyword is a fundamental part of programming. Being used in all popular programming languages like C, C++, or Java, it can essentially be represented as a pointer that points to nothing, or it simply ascertains the fact that the given variable is vacant.
What is NULL
in Python?
Python operates differently from the other popular programming languages. Python defines the NULL
object with the None
keyword instead. These NULL
objects are not valued as 0
in Python though. It does not hold any value whatsoever. This None
keyword in Python is both an object and a None
type data type.
How to check if a variable is NULL
in Python?
Using the is
operator to check if a variable is NULL
in Python.
We can simply use the is
operator or the =
operator to check if a variable is None
in Python.
The following code uses the is
operator to check if a variable is NULL
in Python.
1 2 3 4 5 6 7 |
a = None if a is None: print('a is None') else: print('a is not None') |
The above code provides the following output:
We have made use of the is
operator in this code to check the condition. Alternatively, we can also make use of the ==
operator to complete this task.
The following code implements the same by utilizing the ==
operator.
1 2 3 4 5 6 7 |
a = 16 if a == None: print('a is None') else: print('a is not None') |
The above code provides the following output:
Using the if
condition to check if a variable is NULL
in Python.
We can simply use the if
condition along with no additional operators in order to find out whether the given variable is None
or not.
The following code uses the if
condition to check if a variable is NULL
in Python.
1 2 3 4 5 6 7 |
a = None if a: print('a is not None') else: print('a is None') |
The above code provides the following output:
Using the not equal to
operator to check if a variable is NULL
in Python.
Another method to reveal whether a variable is None
or not in Python is to utilize the !=
or the not equal to
operator.
The following code uses the not equal to
operator to check if a variable is NULL
in Python.
1 2 3 4 5 6 7 |
a = None if a != None: print('a is not None') else: print('a is None') |
The above code provides the following output:
These are the three methods that can be utilized to check whether the given variable is a None
object or not.
Further, we can even check if the given variable is of the None
data type as follows.
1 2 3 4 |
a = None print(type(a)) |
That’s all about how to check for null in Python.