Almost anything in Python can be evaluated into a boolean value. In fact, this is often 'abused' by programmers.
These are some examples of values that evaluate to False
:
false_string = ''
false_int = 0
false_float = 0.0
false_list = []
false_bool = False
if false_string or false_int or false_float or false_list or false_bool:
print('this never gets printed')
However, in most cases there's only one value that evaluates to False
and all other values will evaluate to True
:
true_string = 'false'
true_int = -1
true_float = 0.000001
true_list = [0]
true_bool = True
if true_string and true_int and true_float and true_list and true_bool:
print('this gets printed')
Note that this isn't always obvious. You might think [0]
should evaluate to false, but the list is not empty, so it's True
, even though 0
by itself would be False
.
Whenever you expect a boolean value, just read it as if the value is wrapped in a call to bool()
, i.e.
if x%5:
print('ok')
# is the same as
if bool(x%5):
print('ok')