How to check if the variable is none or Not in Python

Do you want to check if the variable is none or not? If yes then in this post you will learn how to easily check if the variable is none or not in Python. You will know the various methods for that.

Methods to check if the variable is none or Not in Python

Method 1: Using the is operator

In this method you will use the is operator to check whether the variable is none or not.

my_variable = None
if my_variable is None:
    # Code to execute when the variable is None
    print("Yes variable is None")
else:
    # Code to execute when the variable is not None
    print("Yes variable is Not None")

Method 2: Using the == operator

The second is the use of the double equal operator.

my_variable = None
if my_variable == None:
    # Code to execute when the variable is None
    print("Yes variable is None")
else:
    # Code to execute when the variable is not None
    print("Yes variable is Not None")

Method 3: Use of Not operator

You can also use the Not operator directly on the variable to check whether it is None or not.

my_variable = None
if Not my_variable:
    # Code to execute when the variable is None
    print("Yes variable is None")
else:
    # Code to execute when the variable is not None
    print("Yes variable is Not None")

Conclusion

Python provides many different methods to check if the variable is none or Not in Python. Most of the developer uses is and == operator to check the validity of None. The not operator can also be used, but it may produce unexpected results with non-boolean types. 

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link