Control flow · Lesson 4 of 18 · 16 min

Branching and truth

if, else, match, and the truthiness rules underneath.

  • Use truthiness deliberately
  • Write clean if/elif/else chains
  • Reach for match/case on structured data

Conditions are expressions

`if` does not require a boolean. It asks whether the value is truthy. The empty values `0`, `0.0`, `''`, `[]`, `{}`, `set()`, and `None` are falsey. Almost everything else is truthy, including `'False'` the string and `[0]` the one-element list.

That rule is why `if items:` is the idiomatic 'is there anything here?' and why `if count:` is dangerous when 0 is a valid count you need to handle.

Truthiness in practice
for value in [0, 1, "", "0", [], [0], {}, None, "False"]:
    print(repr(value), bool(value))

elif is exclusive

Python has no `switch` of the C kind. `if / elif / else` is a single chain: the first true branch runs, and the rest are skipped. Order matters. Put the more specific conditions first.

From 3.10, `match/case` gives structural pattern matching: you can match literals, sequences, mappings, and class shapes. A case with a guard (`case x if x > 0:`) keeps the pattern narrow. `_` is the wildcard.

match on a command tuple
def handle(event):
    match event:
        case ("click", x, y):
            return f"click at {x},{y}"
        case ("key", name) if name.isalpha():
            return f"letter {name}"
        case ("key", name):
            return f"key {name}"
        case _:
            return "ignored"

for e in [("click", 4, 9), ("key", "a"), ("key", "1"), ("quit",)]:
    print(e, "->", handle(e))

Check yourself

Quiz

  1. 1.Is `[0]` truthy?

  2. 2.What does `'a' or 'b'` return?

  3. 3.In match/case, `_` means:

Practice

Exercise

Write `grade(score)` that returns 'A' for 90+, 'B' for 80+, 'C' for 70+, 'D' for 60+, otherwise 'F'. Scores outside 0–100 should return 'invalid'.

Tutor

Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.