Decisions

if, elif, else, and nested conditions.

if runs a block when a condition is true. Indentation (4 spaces) is the block. This notebook inserts 2 spaces on Tab — either width is fine if you stay consistent in a cell.

Goal

Write if / elif / else and nest a second check.

if / else

score = 91
if score >= 90:
    print("pass with distinction")
else:
    print("keep going")

elif chain

score = 88
if score >= 90:
    band = "A"
elif score >= 80:
    band = "B"
elif score >= 70:
    band = "C"
else:
    band = "D"
print(band)

Python uses elif, not else if.

Combine conditions

city = "Nairobi"
units = 12
if city == "Nairobi" and units >= 10:
    print("bulk Nairobi order")
elif city in {"Mombasa", "Kisumu"}:
    print("coast / lake")
else:
    print("other")

Nested

name = "Ada"
score = 95
if name:
    if score >= 90:
        print(f"{name} is top band")
    else:
        print(f"{name} has a score")

Prefer and on one line when both must be true — nested if is for a second decision that only makes sense inside the first.

Pitfall

A missing colon after if score >= 90 is a SyntaxError. A wrong indent is an IndentationError.