Last modified: Jan 10, 2023 By Alexander Williams
How to Properly Check if a Variable is Not Null in Python
To checkย if a Variable is not Null in Python, we can use 3 methods:
- Method 1: variable is not None
- Method 2: variable != None
- Method 3: if variable:
Note: Python programming uses None instead of null.
1. Checkย if the Variable is not null [Method 1]
The first method is using "is", "not" and "None" keywords. Let's see the syntax, Then the examples.
Syntax
variable is not None
Example 1: Check String Variable
my_var = "Hello Python" # ๐๏ธ String Variable
# ๐ Check if my_var is not Null
if my_var is not None: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
True
The above program returns True if the variable is not null. If null, it returns False.
As you can see, in the output, the program returns True.
Example 2: Check None Variable
my_var = None # ๐๏ธ None Variable
# ๐ Check if my_var is not Null
if my_var is not None: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
False
The program returned False because my_var is None (null).
Example 3: Check Empty Variable
my_var = "" # ๐๏ธ Empty Variable
# ๐ Check if my_var is not Null
if my_var is not None: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
True
We got True Because my_var is empty, not None
2. Checkย if the Variable is not null [Method 2]
The second method for checking if the variable is not null is usingย the != operator + None keyword.
Syntax
variable != None
Example 1: Check String Variable
my_var = "Hello Python" # ๐๏ธ String Variable
# ๐ Check if my_var is not Null
if my_var != None: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
True
Example 2: Check None Variable
my_var = None # ๐๏ธ None Variable
# ๐ Check if my_var is not Null
if my_var != None: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
False
Example 3: Check Empty Variable
my_var = "" # ๐๏ธ Empty Variable
# ๐ Check if my_var is not Null
if my_var != None: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
True
3. Checkย if the Variable is not null [Method 3]
The third method isย the if condition. This method returnsย False if the variable is None or empty.
Syntax
if variable:
Example 1: Check String Variable
my_var = "Hello Python" # ๐๏ธ String Variable
# ๐ Check if my_var is not Null
if my_var: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)
Output:
True
Example 2: Check None Variable:
my_var = None # ๐๏ธ None Variable
# ๐ Check if my_var is not Null
if my_var: # ๐๏ธ Check if my_var is not None (null)
print(True)
else:
print(False)