Selection with if, elif and else
Making a program take one path or another according to a condition, including several branches tested in order until one fits.
What a learner can do afterwards
- Write an if and else that react to a value the user typed
- Use a chain of branches so exactly one of several messages appears
- Explain why reordering the branches changes the result
1 · Read
Selection picks one road for the program to walk. If the test is true its block runs, elif tries the next test, and else sweeps up everything left over. In Python the blocks are marked by indentation, so lining up wrongly means thinking wrongly.
A grading program tests from the top: if mark >= 90 print A, elif mark >= 70 print B, else print Fail. A mark of 82 skips A, matches B, and stops there. Only the first true branch ever runs.
Order changes the result, so always test the highest boundary first. A mark like 95 would match a lower test too, and the chain stops at the first match. Tests can also sit inside other tests, and a whole if and else that only sets one value can shrink to a single line.
Try every road before you trust the chain: the true case, the false case, and each elif in turn.
First true branch wins, so order your tests from strictest to loosest.
2 · Watch
Take it off screen
Where it sits
Learn first
This opens up
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.