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.
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.
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?
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.
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.
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 type | Python | Java |
|---|---|---|
| Count-controlled | for i in range(n): | for (int i = 0; i < n; i++) |
| Pre-condition | while condition: | while (condition) |
| Post-condition | while True: with an if condition: break at the end | do { ... } 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.
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.
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 == "").
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.
Step 2. First try: Ruby presses Enter without typing anything. name is still "", attempts becomes 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".
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.
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.
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.
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.
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
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.
[2]Explain the difference between a pre-condition loop and a post-condition loop.
Marking points
评分要点
- A pre-condition loop checks its condition before each iteration, so if the condition is false at the start the body runs zero times.
- A post-condition loop checks its condition after each iteration, so the body always runs at least once.
- 前测循环在每次迭代之前检查条件,所以如果一开始条件为假,循环体运行零次。
- 后测循环在每次迭代之后检查条件,所以循环体至少运行一次。
[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.
Marking points
评分要点
- (a) printing every element of a 30-item list: count-controlled, because the number of repetitions is known.
- (b) asking for a PIN until it is correct: post-condition, because you must ask at least once and do not know how many tries it will take.
- (c) a pre-condition loop, because the number of repetitions is not known in advance and the body may need to run zero times.
- (a) 打印一个 30 项列表的每个元素:计数控制,因为重复次数已知。
- (b) 反复要求输入 PIN 直到正确:后测,因为必须至少问一次,且不知道要试多少次。
- (c) 前测循环,因为重复次数事先未知,且循环体可能需要运行零次。
[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.
Marking points
评分要点
- The loop's stopping condition depends on a variable that the body never updates with the newly entered PIN, so it keeps comparing the old value.
- Or the comparison is wrong, for example comparing a number to a string, or using = instead of ==, so it is never satisfied.
- The loop control variable must be refreshed with the latest input inside the loop, and compared correctly, so the condition can become false.
- 循环的停止条件依赖一个变量,而循环体从不用新输入的 PIN 更新它,所以它一直在比较旧值。
- 或者比较有误,例如把数字和字符串比较,或用 = 而不是 ==,所以条件永不满足。
- 循环控制变量必须在循环内部用最新的输入刷新,并正确比较,条件才能变为假。
Flashcards
Active recall for this statement’s key terms.
Keep this statement’s practice with you
Free account: unlock every revision question and flashcard for B2.3.3, and every other IB CS 2027 statement.