Here are the three ways to check if a variable is not null in Python:
- Using is not operator
- Using if condition
- Using != operator
Method 1: Using is not operator
The most straightforward way is to use an is not operator to check if a variable is not None.
There is no null in Python, instead, there is None(represent null or absence of value).
Visual Representation
Example
my_var = "AppDividend"
my_var_2 = None
# Check if the variable is not null
if my_var is not None:
print("The variable is not null.")
else:
print("The variable is null.")
if my_var_2 is not None:
print("The variable is not null.")
else:
print("The variable is null.")
Output
The variable is not null.
The variable is null.
Remember that other values such as 0, False, empty strings (“”), and empty lists ([]) are considered valid values and are different from None.
Let’s understand this with an example:
my_var = ""
if my_var is not None:
print("The variable is not null.")
else:
print("The variable is null.")
Output
The variable is not null.
Method 2: Using if condition
There are certain values considered ‘falsy’, including None, False, empty strings, lists, dictionaries, tuples, sets, 0, and 0.0.
If you want to check if a variable is not any of these falsy values, then use an if condition.
Visual Representation
Example
# Define three variables with different values
my_var = "" # An empty string
my_var_2 = None # None
my_var_3 = "AppDividend" # A non-empty string
if my_var:
print("The variable is not null.")
else:
print("The variable is null.")
if my_var_2:
print("The variable is not null.")
else:
print("The variable is null.")
if my_var_3:
print("The variable is not null.")
else:
print("The variable is null.")
Output
The variable is null.
The variable is null.
The variable is not null.
Method 3: Using != operator
You can use the != operator to compare a variable with None.
If they are not equal, it returns True; otherwise, it returns False.
Visual Representation
Example
my_var = "AppDividend"
my_var_2 = None
if my_var != None:
print("The variable is not null.")
else:
print("The variable is null.")
if my_var_2 != None:
print("The variable is not null.")
else:
print("The variable is null.")
Output
The variable is not null.
The variable is null.