Combining conditions
Real rules are rarely a single test. A ticket sale needs the buyer to be an adult AND have ID. An alert fires when a reading is too low OR too high. Logical operators let one condition state the whole rule, instead of stacking nested ifs that each check one piece.
Three logical operators combine True/False values:
| Expression | True when |
|---|---|
a and b | both are true |
a or b | at least one is true |
not a | a is false |
age = 20 has_id = True age >= 18 and has_id # True: both hold age < 18 or age > 65 # False: neither holds not has_id # False
Python also lets you chain comparisons like math notation: 0 <= age <= 30 means age is between 0 and 30, no and needed.
Precedence: not binds tightest, then and, then or. So a or b and c means a or (b and c). When mixing them, use parentheses and spare the reader the puzzle.
Code exercise · python
Run this and check each printed True/False against the table above.
Quiz
With `x = 5`, what does `not (x > 3 and x < 10)` evaluate to?
Code exercise · python
Your turn. A year is a leap year when it is divisible by 4 AND not divisible by 100, OR divisible by 400. Build that as one True/False expression (a bool) with `%`, `and`, `or`, and print it. For 2000 it should print `True` (try 1900 afterwards: it prints False).
Code exercise · python
One more, straight from an online store. Free shipping applies when the order total is at least 50 OR the customer is a member. Build `free_shipping` as one True/False expression and print it.