Lesson 2.3: Use Else and Else If
An else branch runs when the matching if condition is false. An if with else chooses exactly one of two branches.
Use else if when there are more than two cases. Conditions are checked from top to bottom. The first true branch runs, then the rest of that chain is skipped. An ending else handles any value that did not match an earlier condition.
Branch order matters. Suppose a program checks score >= 50 before score >= 100. A score of 120 matches the first rule, so the later rule never gets a turn. The more specific score >= 100 rule should come first.
Guided practice
Create a variable named size. Build these ordered branches:
- If
size >= 10, printlarge. - Else if
size >= 5, printmedium. - Else, print
small.
Test 12, 7, and 3. Then test the boundary values 10 and 5. Record which branch runs for each input and explain why only one branch runs.
Loading the block workspace...
Ready to move on?
Only mark complete if you genuinely understand the material. Your progress will be saved in this browser.
Stuck on this lesson?
Ask about anything on this page. It can see which lesson you have open and which part you are reading.