Boolean logic expressions, in addition to evaluating to True
or False
, return the value that was interpreted as True
or False
. It is Pythonic way to represent logic that might otherwise require an if-else test.
The and
operator evaluates all expressions and returns the last expression if all expressions evaluate to True
. Otherwise it returns the first value that evaluates to False
:
>>> 1 and 2
2
>>> 1 and 0
0
>>> 1 and "Hello World"
"Hello World"
>>> "" and "Pancakes"
""
The or
operator evaluates the expressions left to right and returns the first value that evaluates to True
or the last value (if none are True
).
>>> 1 or 2
1
>>> None or 1
1
>>> 0 or []
[]
When you use this approach, remember that the evaluation is lazy. Expressions that are not required to be evaluated to determine the result are not evaluated. For example:
>>> def print_me():
print('I am here!')
>>> 0 and print_me()
0
In the above example, print_me
is never executed because Python can determine the entire expression is False
when it encounters the 0
(False
). Keep this in mind if print_me
needs to execute to serve your program logic.
A common mistake when checking for multiple conditions is to apply the logic incorrectly.
This example is trying to check if two variables are each greater than 2. The statement is evaluated as - if (a) and (b > 2)
. This produces an unexpected result because bool(a)
evaluates as True
when a
is not zero.
>>> a = 1
>>> b = 6
>>> if a and b > 2:
... print('yes')
... else:
... print('no')
yes
Each variable needs to be compared separately.
>>> if a > 2 and b > 2:
... print('yes')
... else:
... print('no')
no
Another, similar, mistake is made when checking if a variable is one of multiple values. The statement in this example is evaluated as - if (a == 3) or (4) or (6)
. This produces an unexpected result because bool(4)
and bool(6)
each evaluate to True
>>> a = 1
>>> if a == 3 or 4 or 6:
... print('yes')
... else:
... print('no')
yes
Again each comparison must be made separately
>>> if a == 3 or a == 4 or a == 6:
... print('yes')
... else:
... print('no')
no
Using the in operator is the canonical way to write this.
>>> if a in (3, 4, 6):
... print('yes')
... else:
... print('no')
no