Code

And, Or, Not

You can put an if inside another if (a nested decision):

if has_ticket:
    if not storm:
        print("Board the ship")

But it's often clearer to combine conditions with logical operators:

Operator True when…
a and b both are true
a or b at least one is true
not a a is false
if has_ticket and not storm:
    print("Board the ship")

if day == "Sat" or day == "Sun":
    print("Market day!")

Write each comparison in full. day == "Sat" or "Sun" looks right, but it is always true! Python reads it as (day == "Sat") or ("Sun"), and "Sun" on its own always counts as true.

You can also chain comparisons: 0 < x < 10 means 0 < x and x < 10.

Assignment

  1. Complete can_cross(weight, has_pass, storm): return True only if the traveller has a pass, weight is 100 or less, and there is no storm. Otherwise return False.
  2. Complete needs_lantern(hour): return True if hour is before 6 or 20 and later, otherwise False.