Course outline · 0% complete

0/27 lessons0%

Course overview →

elif, and, or

lesson 4-3 · ~10 min · 14/27

More than two branches

Real rules rarely come in pairs: letter grades have five bands, shipping costs have weight tiers, tax has brackets. Programs need a clean way to pick one outcome out of several, and chaining separate if/else statements inside each other gets unreadable fast — so Python provides a flat chain instead. elif (short for "else if") chains extra conditions. Python checks them top to bottom and runs only the first one that is True:

score = 72
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")

With score = 72: is 72 ≥ 90? No. Is 72 ≥ 80? No. Is 72 ≥ 70? Yes, print C and skip the rest. Order matters: put the strictest condition first, or an earlier looser one will steal the match.

Code exercise · python

Run it, then try score = 91, score = 80, and score = 12 and predict each result before running.

Combining conditions

Three words let you build compound conditions from the comparisons in lesson 4-1:

  • and: True only when both sides are True
  • or: True when at least one side is True
  • not: flips True to False and back
age = 25
has_ticket = True
if age >= 18 and has_ticket:
    print("Welcome in!")
else:
    print("Sorry, no entry.")

Note that has_ticket holds a boolean directly, so it can be used as a condition all by itself. No has_ticket == True needed, the variable already is True or False.

Quiz

is_weekend = False and is_holiday = True. What does (is_weekend or is_holiday) evaluate to?

Code exercise · python

Your turn. temperature is 5. Write an if/elif/else that prints "hot" when temperature ≥ 30, "warm" when temperature ≥ 15, and "cold" otherwise.