Python Basics · Making Decisions · lesson 8 of 12
and, or and not
about 10 minutes · free · runs in your browser
Step 1 of 2
Combining conditions
Three words let you build bigger conditions out of smaller ones:
and— true only when both sides are trueor— true when either side is truenot— flips a boolean
if age >= 18 and has_ticket:
print("Come in")
if day == "Saturday" or day == "Sunday":
print("Weekend")
Python is lazy about these, which is more useful than it sounds. In a and b, if a
is false it never looks at b — so if items and items[0] == "x": is safe even when
items is empty.
Your turn: write can_ride(height, age) returning True only when the person is
at least 120cm and at least 8 years old.
You start from this, and edit it in the browser:
def can_ride(height, age):
# Return True only if both conditions are met.
pass
Step 2 of 2
not, and readable conditions
not inverts:
if not logged_in:
print("Please log in")
That reads better than if logged_in == False:, and it is what experienced Python
programmers write.
When conditions get long, brackets make the grouping explicit. and binds tighter than
or, so a or b and c means a or (b and c) — rarely what anyone intends. Put the
brackets in.
Your turn: write needs_review(score, flagged) returning True when the score is
below 40 or the item is flagged — but False for anything scoring 90 or more, no
matter what.
You start from this, and edit it in the browser:
def needs_review(score, flagged):
# Return True when it needs review.
pass