To check if a variable is not None, you can use the inequality operator != and check if the variable is not equal to None.
a = None
b = "Not None"
if a != None:
print("a is not None")
if b != None:
print("b is not None")
#Output:
b is not None
You can also use the is keyword combined with the not keyword to check if a variable is not None.
a = None
b = "Not None"
if a is not None:
print("a is not None")
if b is not None:
print("b is not None")
#Output:
b is not None
When working with variables in Python, the ability to check if a variable is a specific type easily is valuable.
One such case is if you want to check if a variable is not None.
The None keyword is used to define a null value. You can use None to set a variable to null and another case where you might get None is if you have a function which doesn’t return a value.
You may want to check if a variable is not None in the case that you have code which depends on a variable having a valid value.
To check if a variable is equal to not None, you can use the inequality operator != and check if the variable is not equal to None.
Below shows you an example of how you can check if a variable is not None in Python.
a = None
b = "Not None"
if a != None:
print("a is not None")
if b != None:
print("b is not None")
#Output:
b is not None
You can also use the is keyword combined with the not keyword to check if a variable is not None.
a = None
b = "Not None"
if a is not None:
print("a is not None")
if b is not None:
print("b is not None")
#Output:
b is not None
Hopefully this article has been useful for you to learn how to check if a variable is not None.