Quarry School

Combine two conditions — quick review

In plain words

Here are two signs invented for this lesson.

Rule

When A and B are each True or False: A and B is True only if both are True. A or B is True if at least one is True. not A is True if A is False, and False if A is True.

Without parentheses, comparisons group first, then not, then and, then or. Python works out the left side of and or or first, and works out the right side only when the left side has not settled the answer.

Step

  1. Write the rule in words and underline each joining word: and, or, not.

  2. Write each part as a complete condition. A part is a comparison with its own left side, operator and right side, such as height >= 120, or a name that already holds True or False, such as has_ticket.

  3. Where the rule negates a part, write not in front of that part, such as not has_coat.

  4. Join the parts with and where both must hold and with or where one is enough.

  5. If the rule mixes and with or, put parentheses around the part the rule treats as one group, as in (member or total > 50) and coupon.

  6. Fill in a small table with one row for each case of the parts, True or False, and work out the whole condition for every row.

Trap

Each side of and or or must be an expression that stands on its own. English lets you say "older than 12 and younger than 18". In Python, < 18 is not an expression, so age > 12 and < 18 stops with a SyntaxError. Write age > 12 and age < 18.

The slip that raises no error is reply == "y" or "yes". Python reads it as (reply == "y") or "yes". The right side is the text "yes" on its own, and Python counts any text that is not empty as true. The condition therefore passes for every reply. Write reply == "y" or reply == "yes".

When and and or share a line, and groups more tightly. member or total > 50 and coupon means member or (total > 50 and coupon). If you mean the other grouping, write the parentheses.