Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 03 / Topic 1 of 12

if / elif / else

Python checks each condition from top to bottom. The first one that is True runs, and the rest are skipped. else runs only when no condition was True. The block under each line must be indented (4 spaces).

Real-world example: give a grade from exam marks.

marks = 72

if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "Fail"

print(f"Marks {marks} -> Grade {grade}")  # Marks 72 -> Grade C
Keyword How many allowed When it runs
if exactly 1 (first) condition is True
elif 0 or more earlier ones were False and this is True
else 0 or 1 (last) all conditions were False

๐Ÿ” Going deeper: a condition does not have to be a bool. Python checks its truthiness: 0, "", None and empty collections count as False. So if name: means "if name is not empty". Order your elif checks from most specific to least specific.

Read more: the official tutorial's control flow chapter.

Done here? The practice set for Part 3 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide