
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
- Complete
can_cross(weight, has_pass, storm): returnTrueonly if the traveller has a pass,weightis 100 or less, and there is no storm. Otherwise returnFalse. - Complete
needs_lantern(hour): returnTrueifhouris before 6 or 20 and later, otherwiseFalse.
- Complete
can_cross(weight, has_pass, storm): returnTrueonly if the traveller has a pass,weightis 100 or less, and there is no storm. Otherwise returnFalse. - Complete
needs_lantern(hour): returnTrueifhouris before 6 or 20 and later, otherwiseFalse.
main.py Python sleeping
Press Run to try your code, then Check to test it.