Skip to content
Combining Conditions
step 1/8

Reading — step 1 of 8

Learn

~3 min readMaking 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

python

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):

  1. not
  2. and
  3. or

So a or b and c means a or (b and c) — NOT (a or b) and c. Whenever in doubt, add parentheses:

python

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:

python

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:

python

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 canonical worked example: leap year

The leap-year rule is deceptively tricky:

  • Years divisible by 4 are leap years…
  • …except centuries (divisible by 100), which are NOT leap years…
  • …unless they're also divisible by 400, which ARE leap years.

All three rules collapse to one expression:

python

Sanity-check it against famous edge cases: 2024 ✓ leap (divisible by 4, not by 100). 1900 ✗ not leap (divisible by 100, not 400). 2000 ✓ leap (divisible by 400). 2023 ✗ not leap (not divisible by 4 at all).

Common mistakes

  • Forgetting parens with mixed operators: is_open and is_weekend or is_holiday is (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. Use if 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…