← Lectures·L4

Control Flow & Order of Operations

Prof. Dr. Nicolas Rohleder, Prof. Dr. Björn Eskofier, Veronika Ringgold, Luca Abel · 6 concepts · 10 questions

Concept 1 / 6

Chained if/elif/else vs. Independent if Statements

Python offers two distinct ways to branch on multiple conditions, and choosing the wrong one is a common source of subtle bugs.


Chained `if`/`elif`/`else` — the interpreter evaluates conditions one at a time and stops as soon as one is True. At most one body executes:


x = 5
if x > 10:
    print("big")
elif x > 3:
    print("medium")   # ← this runs; the elif below is skipped
elif x > 0:
    print("small")
else:
    print("non-positive")

Separate `if` statements — each if is evaluated independently, regardless of what happened before. Multiple bodies can execute:


x = 5
if x > 10:
    print("big")
if x > 3:
    print("medium")   # ← runs
if x > 0:
    print("small")    # ← also runs
else:
    print("non-positive")

The key rule: use a chained if/elif/else when the conditions are mutually exclusive or when finding one match should skip the rest. Use separate if blocks when multiple conditions can and should all be tested independently.