Last updated: Jun 15, 2022
Photo from Unsplash
Use the boolean OR operator to convert None to 0 in Python, e.g.
result = None or 0. The boolean OR operator returns the value to the left if
it's truthy, otherwise the value to the right is returned. Since
None is a
falsy value, the operation will return
some_number = None result = some_number or 0 print(result) # 👉️ 0
We used the
operator to return
0 if the value to the left is falsy.
All values that are not truthy are considered falsy. The falsy values in Python are:
0(zero) of any numeric type
x or yreturns the value to the left if it's truthy, otherwise the value to the right is returned.
None is a falsy value, the expression
None or y is always going to
x or ywould also return
xis any of the other falsy values, e.g. an empty string,
False, or an empty list, dict or tuple.
Alternatively, you can use an
if statement to check if the variable stores
None and reassign it to
some_number = None if some_number is None: some_number = 0 print(some_number) # 👉️ 0
None is much more explicit and the
if block will only run if
the variable stores a
The condition wouldn't be satisfied if the variable stores any other falsy value.
You can also use a one-liner
some_number = None some_number = 0 if some_number is None else some_number print(some_number) # 👉️ 0
If the variable stores
None, it gets set to
0, otherwise it gets set to its
some_number = 100 some_number = 0 if some_number is None else some_number print(some_number) # 👉️ 100