The idiomatic way to check if a variable is None in Python is to use the “is” operator. To check if a variable is not None, use the “is not” operator.
None represents the absence of value, and when you are performing arithmetic operations, you need to check if the variable is not None; otherwise, it will return either an error or unexpected results.
Null or None safety checks prevent errors when working with potentially uninitiated variables.
Using the is operator
The is operator checks the identity of the objects and not the value, since None is a singleton. That is the main reason for its accuracy. It uses the memory address of objects (accessible via id()).
input = None
if input is None:
print("The variable is None")
else:
print("The variable is not None")
# Output: The variable is None
Using the is not operator
The is not operator compares object identities and then negates the result. It is highly recommended to check the singleton objects. Don’t use for value comparison. For that, use the != operator.
input = 21
if input is not None:
print("The variable is not None")
else:
print("The variable is None")
# Output: The variable is not None
Since 21 is not None, if condition is True, it prints its statement.
You can use both “is” and “is not” operators, but make sure to write conditions based on them.
Why should you not use the “==” operator?
When checking for None, the double equal operator (==) works, but it is not the recommended way. Why? Because the == checks equality (whether two objects have the same value). It does not check the identity.
Another flaw is that some objects (e.g., custom classes) can override __eq__ to return True when compared to None, making == unreliable.
input = None
if input == None:
print("Variable is None")
else:
print("The variable is not None")
# Output: Variable is None
You can also use the != operator, which checks the value too and works with None, but again, it is not a recommended way.
input = 21
if input != None:
print("Variable is not None")
else:
print("The variable is None")
# Output: Variable is not None
Distinguishing None from Falsy Values
Not only is None a falsy value, but 0, [], “”, False values are too!
For checking other values except None, you can use the “not” operator, but for None, use the “is” operator.
val = None
if not val:
print("Falsy")
# Output: Falsy
if val is None:
print("Is None")
# Output: Is None
That’s all!


