Contents
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.
Leave a Reply