First exams 2027 · SL & HL

B2.3.3 · Programming constructs

Loops: repeating without repeating yourself

A carnival announcer doesn't write eight separate announcements for eight lanes. A loop is what lets one instruction, written once, run again and again.

Core for SL & HL Typically 2–5 marks · AO3 Command term: construct

Explainer

At Bellbrook Primary's swimming carnival, the announcer reads out the same kind of line for every lane, every race, all day. Nobody writes that line out eight separate times, they write it once and repeat it.

Df

A loop repeats a block of code, either a set number of times, or for as long as a condition stays true. The termination condition is whatever eventually makes the repetition stop.

Explainer

Three types of loop

The three types differ in exactly one thing: when is the number of repetitions actually known, and when is the condition checked?

1

Count-controlled (FOR) loop. The number of repetitions is known before the loop even starts. There are always 8 lanes, so a loop announcing every lane always runs exactly 8 times, no condition needed.

2

Pre-condition (WHILE) loop. The condition is checked before every pass. If it's already false the very first time, the loop body might not run at all.

3

Post-condition (REPEAT-UNTIL) loop. The order flips: the body runs first, and only once it's finished does the program decide whether to run it again. That guarantees at least one run, no matter what.

Loop typePythonJava
Count-controlledfor i in range(n):for (int i = 0; i < n; i++)
Pre-conditionwhile condition:while (condition)
Post-conditionwhile True: with an if condition: break at the enddo { ... } while (condition);

Python has no dedicated REPEAT-UNTIL keyword. It's written as an always-true WHILE loop that deliberately breaks itself once the real condition is met, Java has a genuine do-while for this.

Two more real terms from the syllabus

Validation is checking that input is sensible or reasonable at all, like refusing an empty name. Verification is checking that input was copied down accurately, like asking someone to type their password twice and comparing the two entries. Both are common reasons to reach for a loop: keep asking until the input passes the check.

Explainer

A condition inside a loop is a different job to the loop's own condition

A loop's own condition decides whether to keep looping at all. An IF statement written inside the loop's body decides what happens on this one pass, it doesn't affect whether the loop keeps going. A loop can use both at once: the loop's own exit test can combine a relational operator with a Boolean operator (attempts < 3 and name == ""), and, separately, the body can contain its own IF using relational operators to react to whatever this pass's value is.

Worked example

Announcing every lane: a count-controlled loop

8 lanes, always. The number of repetitions never depends on anything the program has to check.

for lane in range(1, 9): print("Lane", lane, "ready")
Lane 1 ready Lane 2 ready Lane 3 ready ... Lane 8 ready

range(1, 9) produces 1 up to and including 8, eight values in total, matching the eight real lanes exactly.

Worked example

Signing a swimmer in: a pre-condition loop

A sign-in kiosk won't accept a blank name, but it also won't hold up the whole carnival forever: it gives up after 3 tries. The loop's own condition combines a relational operator (attempts < 3) with a Boolean operator (and) with an equality check (name == "").

Ruby signs in, on her second try Step 1 of 4

Step 1. Before the loop, name is empty and attempts is 0. The loop's condition is checked first: name == "" is True, and attempts < 3 is True, so the loop body runs.

name = "" attempts = 0 while name == "" and attempts < 3: name = input("Enter swimmer name: ") attempts = attempts + 1

Step 2. First try: Ruby presses Enter without typing anything. name is still "", attempts becomes 1.

name = "" attempts = 1

Step 3. The condition is checked again: name == "" is still True, attempts < 3 is still True. Ruby gets a second try, this time she types "Ruby".

name = "Ruby" attempts = 2

Step 4. The condition is checked a third time: name == "" is now False. The AND makes the whole condition False, so the loop stops, after only 2 of the 3 allowed attempts.

print("Signed in:", name)
Signed in: Ruby

Try it yourself

Run the sign-in loop

This is the real input(), exactly as shown in the worked example above. Press Run, then answer the browser's prompt each time the loop asks, the dialog itself shows the actual message Python is printing. Type nothing (or Cancel) to see it ask again, up to 3 tries, or type a name to finish early.

main.py
Loading Python engine…
Output
Press Run to see the output here.

Running in offline fallback mode. The full Python engine couldn't load (blocked school network, or no internet), so this console switched automatically to a small hand-written engine. It supports this page's loops and conditions, but it isn't full Python.

Worked example

Swimming until enough laps are done: a post-condition loop

A swimmer training for their race must swim at least 4 laps. They always swim the first lap before anyone checks anything, the check only happens once a lap is actually finished. That's exactly what a post-condition loop is for.

laps_done = 0 while True: laps_done = laps_done + 1 print("Finished lap", laps_done) if laps_done >= 4: break
Finished lap 1 Finished lap 2 Finished lap 3 Finished lap 4

Written as a WHILE loop with an always-true condition, the only way out is the break once laps_done >= 4. Even if a swimmer only needed 0 laps (a strange requirement, but imagine it), this shape would still swim one full lap before ever checking, because the check happens at the end of the body, not the start. That's the real difference from a pre-condition loop, which could skip the body entirely.

Worked example

Counting the fast qualifiers: a condition inside a loop

Eight lane times have been recorded for one race. The qualifying time for the next round is 32.0 seconds or faster. The loop itself just visits every lane, once each, a count-controlled loop. Deciding whether a given lane's time actually qualifies is a completely separate job, done by an IF statement inside the loop's body.

lane_times = [31.2, 33.8, 32.0, 34.1, 30.9, 33.0, 31.9, 35.5] qualifiers = 0 for time in lane_times: if time <= 32.0: qualifiers = qualifiers + 1 print("Qualifiers:", qualifiers)
Qualifiers: 4

The FOR loop's own job is just "visit every one of the 8 lane times." The IF inside it is what actually decides which ones count, using a relational operator (<=) that has nothing to do with whether the loop keeps running.

Check your understanding

A pre-condition loop's exit test is while name == "" and attempts < 3:. If a swimmer types a valid name on their very first try, how many times does the loop body run?

Common mistake

Markers reported this pattern on validation-loop questions

RecurringA frequently reported error is writing a loop whose exit condition depends on user input, but placing the actual input statement in the wrong spot, often only before the loop, never repeated inside it. The loop still runs, and it doesn't crash, it just never gives the user a real chance to fix what they typed.

Answer frame that scores: the statement that could change the loop's condition (here, the input read) has to sit inside the loop body, every single pass, not just once beforehand.

✕

Input read once, outside the loop:

name = ""
attempts = 0
name = input("Enter swimmer name: ")

while name == "" and attempts < 3:
    attempts = attempts + 1

If the first entry is empty, name never changes, the loop just burns through 3 attempts doing nothing and never actually asks again.

✓

Input read inside the loop, every pass:

name = ""
attempts = 0

while name == "" and attempts < 3:
    name = input("Enter swimmer name: ")
    attempts = attempts + 1

Now every pass genuinely gives the user another real chance to type something different.

Revision questions

Past-paper style. Write an answer, then reveal the marking points and mark yourself.

Question 1 · 2 marks

[2]Explain the difference between a pre-condition loop and a post-condition loop.

Question 2 · 3 marks

[3]Identify which type of loop, count-controlled, pre-condition or post-condition, is most appropriate for each: (a) printing every element of a 30-item list, (b) asking for a PIN until it's correct, (c) rolling a dice at least once and re-rolling on a 1.

Question 3 · 4 marks

[4]A loop is meant to keep asking for a PIN until it's entered correctly, but the program hangs and never stops asking even when the correct PIN is typed. Suggest what is likely wrong with the loop, referring to where the input statement is placed.

Flashcards

Active recall for this statement’s key terms.