Video lecture
Watch on YouTube(opens in a new tab)Sub topic 6
The Three Building Blocks: Sequence, Selection, Iteration
This chapter assumes you can read simple Python, that you know what if, while and for do in at least one language, and that you have seen Euclid's algorithm described in plain language earlier in this tutorial. The goal here is to look at those familiar constructs as a description language: a small, fixed set of shapes that every algorithm can be built from.
Why only three?
When you wrote Euclid's algorithm as numbered steps, you used only three kinds of instruction:
- Sequence: do this step, then that step ("compute r", then "replace a with b").
- Selection: choose between steps based on a condition ("if b is 0, the answer is a").
- Iteration: repeat steps while a condition holds ("go back to step 1").
These three are enough. In 1966 Corrado Böhm and Giuseppe Jacopini showed that any computation that can be drawn as a flowchart can be rewritten using only sequence, selection and iteration, possibly with some extra Boolean variables. This result is called the structured program theorem. It does not say other constructs such as break, early return or goto are wrong. It says they are conveniences you never strictly need.
This matters for describing algorithms because readers can rely on it. If every step of your description is one of the three shapes, nested inside one another, a reader can follow it without jumping around. "Go back to step 1" is a jump, but it is a disciplined jump: it closes a loop and goes nowhere else.
| Building block | Plain-language signal | Pseudocode form | Python form |
|---|---|---|---|
| Sequence | "then", numbered steps | one statement per line | statements in order |
| Selection | "if", "otherwise" | `if ... then ... else ... end if` | `if` / `elif` / `else` |
| Iteration (condition-controlled) | "repeat while", "until" | `while ... do ... end while` | `while` |
| Iteration (count-controlled) | "for each" | `for each x in S do ... end for` | `for` |
Sequence: order is meaning
A sequence is a list of steps run one after another, each seeing the effects of the ones before. It is the easiest block to overlook, and it causes a surprising number of bugs, because changing the order changes the algorithm.
Consider step 3 of Euclid's algorithm: "Replace a with b, and b with r." A direct translation that drops r looks reasonable:
def gcd_wrong(a, b):
while b != 0:
a = b
b = a % b # a has already been overwritten, so this is b % b
return a
print(gcd_wrong(48, 18)) # prints 18, but gcd(48, 18) is 6After a = b, the old value of a is gone, so a % b is always b % b, which is 0. The loop runs once and returns the wrong answer. The plain-language description avoided this by naming r in step 2 before the replacements in step 3. In Python you can keep the temporary or use simultaneous assignment, which evaluates the whole right-hand side before assigning anything:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6Selection: choosing a path
Selection runs one of several groups of steps depending on a condition. The basic forms are:
- One-way:
if condition then steps. Nothing happens otherwise. - Two-way:
if condition then A else B. Exactly one of A or B runs. - Multi-way: a chain of
if / else if / else. Conditions are tested in order, and the first true one wins.
The phrase "first true one wins" is where many errors come from. When conditions overlap, their order decides the result:
def grade_wrong(score):
if score >= 50:
return "pass"
elif score >= 90: # unreachable: any score >= 90 is already >= 50
return "distinction"
else:
return "fail"
def grade(score):
if score >= 90:
return "distinction"
elif score >= 50:
return "pass"
else:
return "fail"
print(grade_wrong(95), grade(95)) # pass distinctionWhen you write a multi-way selection, check two things:
- Coverage. Every possible input satisfies at least one branch, or you have deliberately decided that nothing should happen. A missing
elseis fine only if you chose it. - Overlap. If two conditions can be true at once, the more specific one comes first. The alternative is to make the conditions mutually exclusive (
50 <= score < 90) so order stops mattering. That is more verbose but safer when other people edit the code later.
Selection also guards against inputs the algorithm cannot handle. Step 1 of Euclid's algorithm is a selection that stops the algorithm before it tries to divide by zero.
Iteration: repeating steps
Iteration repeats a group of steps, called the loop body. There are two flavours, and choosing the right one makes a description clearer.
Count-controlled iteration ("for each item in the list") runs once per element of a finite collection. You know the maximum number of repetitions before the loop starts, so stopping is guaranteed by the size of the collection.
Condition-controlled iteration ("while b is not 0") repeats as long as a condition is true. You usually do not know in advance how many times it will run. Euclid's algorithm is like this: gcd(48, 18) takes 3 iterations, while gcd(89, 55) takes 9. For this kind of loop the reader needs a reason to believe the condition eventually becomes false. A later chapter covers that argument (termination). For now, check that something in the body moves the loop toward its exit.
Common iteration errors:
| Error | Symptom | Example |
|---|---|---|
| Condition never changes | Infinite loop | `while i < n:` with no update to `i` |
| Off-by-one bound | One element skipped or one too many | `range(1, len(xs))` when index 0 also matters |
| Wrong test position | Body runs once when it should run zero times | A "repeat ... until" loop used when the input may already be finished |
| Modifying the collection being iterated | Skipped or repeated elements | removing items from a list inside `for x in xs` |
The third row is about where the test happens. A while loop tests before each pass, so its body may run zero times. A "repeat ... until" (do-while) loop tests after each pass, so its body runs at least once. Euclid's algorithm needs the test first. If b starts at 0, the body must not run, or the algorithm would compute a mod 0.
Nesting: how real algorithms are built
The three blocks combine by nesting. Any step inside a sequence, a branch or a loop body can itself be a sequence, a selection or a loop. Linear search is a selection nested inside an iteration, followed in sequence by one more step:
def linear_search(items, target):
for i, x in enumerate(items): # iteration
if x == target: # selection inside the loop
return i
return -1 # sequence: runs after the loop ends
print(linear_search([4, 8, 15, 16], 15)) # 2
print(linear_search([4, 8, 15, 16], 23)) # -1The early return i leaves the loop from the middle, which is one of the conveniences mentioned earlier. You can write the same algorithm with only the three pure blocks by adding a Boolean flag, as the theorem promises:
def linear_search_structured(items, target):
i = 0
found = False
while i < len(items) and not found:
if items[i] == target:
found = True
else:
i = i + 1
if found:
return i
else:
return -1
print(linear_search_structured([4, 8, 15, 16], 15)) # 2
print(linear_search_structured([4, 8, 15, 16], 23)) # -1The two versions give the same results. The first is shorter. The second makes the exit condition visible in one place, the loop header, which helps when you later want to argue the loop is correct. Neither is better in general. Pick the one that makes your description easiest for your reader to check.
Expressing any procedure with the three blocks
When you turn an informal procedure into an algorithm description, ask these questions in order:
- What are the steps, and in what order? That gives the sequence.
- Where does the next step depend on the data? Each such point is a selection. List every case.
- What repeats? Each repetition is an iteration. Decide whether it runs over a known collection (
for each) or until a condition holds (while), and whether the test should come before or after the body. - What is inside what? Nest the blocks and indent to show it.
If you find yourself writing "go to step 7" from the middle of step 3, stop and check whether you have an unrecognised loop or a selection with a missing branch. Jumps that are not loop-backs usually mean the structure has not been found yet.
Exercise
Label each part of find_max (best = xs[0]; for x in xs[1:]: if x > best: best = x; return best) as sequence, selection or iteration, and describe how they nest.
Show answer
The function is a sequence of three steps: the assignment best = xs[0], a count-controlled iteration over xs[1:], and return best. Inside the iteration the body is a one-way selection (if x > best) whose branch is a single assignment. There is no else, because when x is not larger, nothing should change.
Exercise
A shipping rule reads: "Orders of 100 or more ship free; orders of 50 or more pay 5; orders over 200 get a gift; everything else pays 10." Why can't this be written as one if/elif/else chain in the order given, and how should it be structured?
Show answer
The gift rule is independent of the shipping cost. An order over 200 also qualifies for free shipping, so in a single chain only one of the two would apply. Use a multi-way selection for shipping (>= 100 free, elif >= 50 pay 5, else pay 10), followed in sequence by a separate one-way selection: if total > 200, add a gift.
Exercise
Someone rewrites Euclid's loop as a do-while: repeat { r = a mod b; a = b; b = r } until b == 0. For which valid inputs does this fail, and why?
Show answer
It fails whenever b starts at 0, for example gcd(7, 0). A do-while runs its body before testing, so it computes 7 mod 0 and divides by zero. The precondition allows b = 0, so the test has to come before the body, as in a while loop.