Step 1 of 8 · Reading · ~3 min
Learn
Making Decisions
Real-world decisions are rarely a single yes-or-no. "Can this person rent a car?" depends on age AND license AND credit card. "Should we cancel the outdoor event?" depends on rain OR extreme heat OR a severe-weather warning. Writing these compound boolean expressions correctly — and readably — is a skill every programmer needs.
Combining with and / or
With and, all conditions must be True. With or, at least one must be True.
Operator precedence
When mixing and, or, and not, Python applies them in this order (highest binds tightest):
notandor
So a or b and c means a or (b and c) — NOT (a or b) and c. Whenever in doubt, add parentheses:
When reviewing code, parens around mixed boolean ops are a sign of care. Skipping them is how subtle bugs sneak in.
De Morgan's laws — useful for refactoring
There are two algebraic identities that help simplify negated boolean expressions:
not (A and B) ≡ (not A) or (not B)
not (A or B) ≡ (not A) and (not B)
In practice:
Which form is clearer is a judgment call — but knowing they're equivalent is essential.
Chained comparisons — Python's superpower
Python lets you chain comparisons in a way that matches math notation:
Both < operators must be True for the whole expression to be True. You can chain multiple: 0 <= x < 100. Read it like math: "x is between 0 (inclusive) and 100 (exclusive)."
A worked example: rule, exception, exception-to-the-exception
Real rules are rarely one clause. A library charges a late fee on every overdue book — except for staff members — unless the staff member is more than 30 days late, in which case the fee applies after all. Three clauses, one expression:
The shape is worth memorising, because it recurs constantly: a general rule
and not an exemption, or the narrower case that overrides the exemption.
Walk the edges by hand — a non-staff borrower 2 days late, a staff member 5 days
late, a staff member 45 days late — and check each one against the sentence.
The exercise below is exactly this shape with different arithmetic.
Common mistakes
- Forgetting parens with mixed operators:
is_open and is_weekend or is_holidayis(is_open and is_weekend) or is_holiday— almost never what you wanted. - Comparing one variable to multiple values incorrectly:
if x == 1 or 2:looks right but is WRONG. It evaluates as(x == 1) or 2, which is always truthy because 2 is truthy. Useif x == 1 or x == 2:, or better,if x in (1, 2):. - Negating a chain without thinking:
not (a < b < c)is tricky. Often easier to negate the test you actually want.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…