And, or, not: join yes-or-no questions together
One question is often not enough. Should the bakery warn a customer? Only if the bake has nuts and the customer has an allergy. Three small words let you build rules like that.
The big idea
and is true only when both checks are true, or is true when at least one is, and not flips True to False.
See it in code
and joins two checks. The whole thing is true only when both sides are true:
has_nuts = True
nut_allergy = True
if has_nuts and nut_allergy:
print("Stop! This bake has nuts.")
else:
print("Enjoy your bake!")Stop! This bake has nuts.
Both sides were true, so the warning ran. Change either one to False and the customer gets the friendly message instead.
or is easier to please. It's true when at least one side is true:
how_many = 2
big_order = 10
today = "Friday"
if how_many >= big_order or today == "Friday":
print("A free cookie goes in the bag!")
else:
print("Thanks for your order!")A free cookie goes in the bag!
The order wasn't big, so the first check was false. It is Friday, so the second was true. One true side is all or needs.
not flips an answer. Give it True and you get False, and the other way around. It reads almost like plain English:
cookies_left = 40
is_sold_out = cookies_left == 0
print("Sold out?", is_sold_out)
if not is_sold_out:
print("Taking orders now!")Sold out? False Taking orders now!
is_sold_out was False, so not is_sold_out was True, and the shop took orders. A good variable name makes the line read like a sentence.
Games use these words all the time. A snake crashes if it hits the left wall or the right wall. A ship fires only if space is pressed and it has lasers left.
Try it yourself
In the second program, change today to "Monday" and run it. Then change how_many to 12 and run it again. Which side made the rule true this time?
The common mistake
Mixing up and with or. Ask yourself: do I need both things, or is one enough? An allergy warning needs both. A free-cookie rule needs only one.
What it unlocks
These rules go inside if, elif, and else. Each side of a rule is a comparison, and the same rules can keep a while loop running.