Python elif and Nested Conditions
Core idea
Use elif (else if) when a decision has more than two alternatives. Python tests conditions from top to bottom and executes only the first matching block. An optional else covers everything left. A nested if is another decision inside an already selected block. Use nesting when the second decision should depend on the first.
score = 72if score >= 90: print("High")elif score >= 60: print("Medium")else: print("Low")The first test fails; the second succeeds. For inputs 0 through 100, High covers 90 through 100, Medium 60 through 89, and Low the rest.
Compare independent tests
score = 95if score >= 60: print("Pass")if score >= 90: print("High")These are two independent if statements. Both blocks run. With an if/elif chain, only the first matching branch would run.
Make a nested decision
stock = 3paid = Falseif stock > 0: if paid: print("Ship") else: print("Await payment")else: print("Unavailable")The outer condition succeeds, so payment is checked. The inner else aligns with its own if. When stock is zero, payment is not checked.
Common mistake
For descending threshold rules, test the highest threshold first. Testing score >= 60 before score >= 90 in the same if/elif chain hides the higher category.
Practice
Change score in the first example to 59, 60, 89 and 90. Write down the category for each. Then change stock to 0 in the nested example.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Elif and nested decisions
Check your understanding of elif and nested conditions.
What is printed?
score = 60if score >= 90: print("High")elif score >= 60: print("Medium")else: print("Low")What is printed?
score = 95if score >= 60: print("Pass")if score >= 90: print("High")What is printed?
stock = 0paid = Trueif stock > 0: if paid: print("Ship") else: print("Await payment")else: print("Unavailable")For a descending threshold chain with High >= 90 and Medium >= 60, which test comes first?