The elif (else if) Statement
You'll learn how to check multiple mutually exclusive conditions in sequence using elif to handle complex decision-making scenarios.
What's the Problem with Just if and else?
You already know how to make a two-way decision: "if this, do that; otherwise, do something else." But what if you need to test several different conditions, and only one should execute?
You could nest many if-else statements inside each other, but that quickly becomes messy and hard to read. The elif statement (short for "else if") solves this by letting you chain multiple conditions together cleanly.
How elif Works
Think of elif like a cascade of doors you try in order:
- First, check the
ifcondition. If true, execute that block and skip everything else. - If false, check the first
elifcondition. If true, execute its block and stop. - If false, check the next
elif(you can have many). Keep going until one is true. - If none are true, execute the
elseblock (if you included one).
The key: Only one block ever runs — the first one whose condition is true.
Structure
if condition1:
# runs if condition1 is true
elif condition2:
# runs if condition1 was false AND condition2 is true
elif condition3:
# runs if both above were false AND condition3 is true
else:
# runs if all conditions were false
The conditions are checked in order, from top to bottom. Once one matches, the rest are ignored.
Why It Matters
elif keeps your code readable when you have multiple mutually exclusive cases — like checking grade ranges, handling menu options, or categorizing input. Without it, you'd nest if-else statements multiple levels deep, making code harder to follow.
Key Takeaway: Use elif to test multiple conditions in sequence where only one outcome should execute, keeping your code clean and avoiding deeply nested if statements.