How to check if a variable is None in Python

0
19

In this tutorial, we are going to learn about how to check if a variable is None or not in Python with the help of examples.

Note: None means null value in Python.

Consider, that we have the following variable in our code:

Now, we need to check if the above variable is None or not.

Using is keyword

To check if a variable is None or not, we can use the is keyword in Python.

The is keyword returns True, if both values ​​refer to the same object. Otherwise, it returns false.

Here is an example:


x = None

if x is None:
    print('Variable is None')
else:
    print('Variable is not None')

Output:

In the above code,

  1. We have first initialized a variable with a None value.

  2. Then we used is keyword to check if both values ​​refer to the same object.

If it returns True it prints the variable is Noneif variable is not None then it returns False and prints Variable is not None.

Another example:


y = 10

if y is None:
    print('Variable is None')
else:
    print('Variable is not None')

Output:

Similarly, we can also use the isinstance() function in Python to check if a given variable is None.

x = None

if  isinstance(x, type(None)):
    print('Variable is None')
else:
    print('Variable is not None')

The isinstance() function takes the two arguments, the first argument is objectand the second argument is type then it returns True if a given object is a specified type otherwise it returns False.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here