When working with conditional statements in Python, it’s
important to understand what values evaluate to
True and what values
evaluate to False. While
some values are obviously
True, such as any non-zero
number or a non-empty string, there are a few other values
that can sometimes trip up programmers. In particular, the
values None,
"False", and the
number 0 are all examples
of values that evaluate to
False in Python.
Let’s take a closer look at each of these values and why they
evaluate to False.
None
In Python, None is a
special value that represents the absence of a value. It’s
often used to indicate that a variable or function argument
has not been assigned a value, or to represent the result of a
function that doesn’t return anything. When you use
bool(None) to check if
None is
True or
False, it will always
evaluate to False.
x = None
if x:
print("This won't be printed")
else:
print("x is None")
“False”
The string
"False" may seem
like it would evaluate to
True, since it contains the
word “false”. However, in Python, a non-empty string always
evaluates to True,
regardless of its contents. Therefore, the string
"False" is not
the same as the boolean value
False, and it will evaluate
to True in conditional
statements.
x = "False"
if x:
print("x is non-empty string")
else:
print("This won't be printed")
0
The number 0 may seem like
it would evaluate to True,
since it’s a non-empty value. However, in Python, any numeric
value that is equal to
0 will evaluate to
False. This includes
integers, floats, and other numeric types.
x = 0
if x:
print("This won't be printed")
else:
print("x is 0")
It’s important to keep in mind that while these values
evaluate to False, they
still have a value that can be used in your code. For example,
you can assign None to a
variable, or use 0 in a
calculation. Just be sure to use them in the appropriate
context so that your code behaves as expected.
In conclusion, when writing conditional statements in Python, it’s important to be aware of values that evaluate to False, including None, “False”, and the number 0. You can write more robust and reliable code by understanding how these values behave.