Programming Basics — Sequence, Selection, Iteration
What's covered
Key facts
A for loop is the right choice when you know in advance how many times the code should repeat.
while is the right choice when the number of repeats depends on a condition (e.g. user input) rather than a known count.
Deeply nested code is harder to read and debug, so authors usually refactor (split out functions, use early returns) once nesting goes more than two or three deep.
elif (else-if) lets you test another condition when the previous if was false; the first elif that matches runs and the rest are skipped.
Sequence in programming means running the program's lines one after another in the order they are written.
The counter (the loop variable) keeps track of how many times the loop has run so far.
A standard while loop checks the condition before each pass through the body.
In Python, indentation is what shows which block is inside which — deeper indent means deeper nesting.
A chain of `elif`s tests several alternatives without deep nesting; rewriting them as separate `if`s changes the meaning because the rest of the chain no longer skips.
Lines in a sequence are not picked at random and they do not all run at the same time — they run in the written order, one after another.
Sample questions
A taste of the 53 questions in this topic — answers marked. Sign up to practise the full set with spaced repetition.
When is a FOR loop ideal?
- •When data needs sorting from scratch
- •When the CPU is running at low speed
- ✓When the number of repeats is known
- •When the user might quit the program
What is a WHILE loop?
- •Executes only when a variable equals zero
- ✓Loops while a condition holds
- •Repeats a fixed number of times
- •Runs once then checks if it should stop
When is a nested loop useful?
- •Adding two plain integers together
- •Picking only one item from a list
- •Reading a single line of input
- ✓Working through rows and columns
What does selection let a program do?
- ✓Choose between possible actions
- •Repeat a block of code many times
- •Run instructions one after another
- •Store a value for use later
In what order does a sequence run?
- •Bottom to top of the program
- •In a random order each run
- •Only when the user presses a key
- ✓Top to bottom, line by line
FOR i in range(5) — how many times does the loop run?
- ✓Five times in total
- •Once in total only
- •Six times in total
- •Ten times in total
Try it for four weeks. Free.
One school. Unlimited classes. No card limit. No teacher limit. If your students aren't practising daily by the end of the trial, you owe us nothing.