Combining conditions

Lesson 26 of 54 · Python Foundations

and, or, and not let us express a rule made of smaller conditions. For Boolean operands, and is true when both sides are true; or is true when at least one is true; not reverses a truth value.

A B A and B A or B
False False False False
False True False True
True False False True
True True True True
has_ticket = True
door_open = False
staff = True
print(has_ticket and door_open)
print((has_ticket and door_open) or staff)
print(not door_open)
False
True
True

In the middle expression, the parenthesized part is false, but staff is true, so the result is true. Comparisons bind more tightly than not, which binds more tightly than and, which binds more tightly than or. Parentheses help the reader see the intended grouping.

Python short-circuits: it skips the right operand of and if the left is falsey, and skips the right operand of or if the left is truthy. This makes a guard possible:

count = 0
total = 18
print(count != 0 and total / count > 2)
False

Because count != 0 is false, the division is never evaluated. Beyond Boolean operands, and and or return one of their operands rather than necessarily returning a Boolean. 0, 0.0, empty strings and None are examples of falsey values; nonempty strings are truthy, including "False". not always returns a Boolean. When a variable already holds a Boolean, if has_ticket: is clearer than comparing it to True.

Chapter index