Chapter 2 · Apprentice

if / elif / else

if runs a block of code only when a condition is true. elif ("else if") checks another condition when the ones above were false. else catches everything left over. You can have any number of elifs, and else is optional.

The condition is anything that evaluates to true or false — a comparison like level >= 3, a bool variable, or any value (Python treats 0, "", [], None as falsy and most other things as truthy).

Python uses indentation to mark which lines belong to the block — there are no braces. The line ends in a colon : and the body is indented (4 spaces by convention). Python checks the branches top to bottom and stops at the first true one, so order matters.

Syntax

if condition:
    # runs if condition is true
elif other_condition:
    # runs if the first was false and this is true
else:
    # runs if none above were true

# Comparisons: ==  !=  <  >  <=  >=

Worked examples

Three-way branch (order matters)

def access(level):
    if level >= 3:
        return "admin"
    elif level >= 1:
        return "member"
    else:
        return "guest"

print(access(5))   # admin
print(access(2))   # member
print(access(0))   # guest

if with no else (does nothing when false)

temperature = 38
if temperature > 37.5:
    print("Fever")
# prints "Fever"; if temp were 36, nothing prints

Truthiness — empty things are falsy

name = ""
if name:
    print(f"Hi {name}")
else:
    print("No name given")   # this runs (empty string is falsy)

Common mistakes & gotchas

Order of branches changes the result

Because Python stops at the first true branch, a broad condition placed first can swallow narrower ones. if level >= 1 ... elif level >= 3 would never reach the >= 3 branch — anything 3+ is also ≥1. Put the most specific/highest conditions first.

= instead of == in a condition

if x = 5: is a SyntaxError — assignment isn't allowed in a condition. You want if x == 5: to compare.

Inconsistent indentation

Mixing tabs and spaces, or misaligning the body, raises IndentationError or silently puts a line outside the block. Pick 4 spaces and stay consistent.

Why it matters

Branching is how software responds to different situations — permission levels, valid vs invalid input, success vs failure. Almost every useful program is a tree of decisions, and `if/elif/else` is the trunk.