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.
Table Of Contents
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)