If/else statements choose between two branches, while elif or else if adds further conditions so a program can choose among several branches. Conditions are evaluated from top to bottom, and only the first branch whose condition is true is executed.
A selection statement controls program flow using a Boolean expression, which evaluates to either true or false. In a two-way selection, the if branch runs when the condition is true; otherwise, the else branch runs.
if temperature > 30 then
output "Hot"
else
output "Not hot"
end if
Here, exactly one output is produced. The else clause has no condition because it handles every case not accepted by the preceding if condition.
For more than two alternatives, a selection chain uses elif in Python or else if in many other languages:
if mark >= 80 then
grade = "A"
else if mark >= 70 then
grade = "B"
else if mark >= 60 then
grade = "C"
else
grade = "D"
end if
| Mark | Evaluation and result |
|---|---|
| 85 | First condition is true, so grade becomes A |
| 75 | First is false; second is true, so grade becomes B |
| 65 | First two are false; third is true, so grade becomes C |
| 55 | All conditions are false, so the else branch assigns D |
The order matters. For a mark of 85, several lower thresholds are also satisfied, but the program stops after the first true condition.
A common misconception is that every true condition in an elif chain executes. That would apply to separate if statements, not one connected if/elif/else structure.
Exam technique: For B2.3 Programming constructs, trace conditions in order and state which single branch executes. When writing code, make conditions mutually appropriate, place more restrictive thresholds first, and distinguish a selection chain from independent or nested if statements.