Learn
B2.3.3 | LOOPING STRUCTURES
01 | TEACH A PROGRAM TO REPEAT
Imagine sending a reminder to every student in a class. Copying the same print statement thirty times creates thirty places to edit, and it still fails when the class size changes. A loop expresses the repeated action once and controls how often it happens.
Iteration means repetition. One iteration is one execution of the repeated block. That block is called the loop body. The body may contain several instructions, including calculations, selections and other loops.
This SL/HL lesson constructs Python and Java loops, chooses appropriate stopping rules and traces the changing state. We start with small examples before building complete solutions.
02 | FIND THE BODY AND THE NEXT INSTRUCTION
for number in range(1, 4):
print("Round", number)
print("Keep going")
print("Finished")
The two indented print statements form the body. They run together for number 1, then 2, then 3. Finished is outside the body, so it runs once after the loop finishes normally.
Python uses a colon and indentation to identify the body. Moving Finished to the same indentation as the other prints would make it repeat three times. Trace the indentation, not just the order of the words.
03 | FOR: REPEAT FOR A KNOWN SEQUENCE
for attempt in range(3):
print("Practice attempt", attempt)
A Python for loop takes each item from an iterable in turn. An iterable is something that supplies items for iteration, such as a range, string or list. Here range(3) supplies 0, 1 and 2, so the body runs three times.
The loop assigns the next item to attempt before each execution of the body. You do not need to write attempt = attempt + 1 in this loop.
A range is useful when repetition is controlled by a count. A Python for is not restricted to counting, as we will see when visiting a list.
04 | RANGE: START INCLUDED, STOP EXCLUDED
| Expression | Values visited | Iterations |
|---|---|---|
| range(4) | 0, 1, 2, 3 | 4 |
| range(1, 5) | 1, 2, 3, 4 | 4 |
| range(2, 9, 2) | 2, 4, 6, 8 | 4 |
| range(5, 0, -1) | 5, 4, 3, 2, 1 | 5 |
| range(3, 3) | No values | 0 |
range(start, stop, step) includes its start when the range is nonempty, but never includes stop. The default start is 0 and default step is 1. A negative step counts down; step 0 is invalid.
To visit 1 to 5 inclusive, use range(1, 6). To count down from 5 to 1, use range(5, 0, -1). If the step moves away from the stop from the start, the range is empty rather than automatically reversing direction.
05 | COUNTING DOWN AND ZERO ITERATIONS
for seconds in range(3, 0, -1):
print(seconds)
print("Go")
for value in range(5, 2):
print("This body is skipped")
The countdown outputs 3, 2, 1, then Go. The second range has a positive default step but starts above its stop, so it has no items and its body never runs.
Do not assume every loop executes at least once. Include an empty collection or zero repetition count in your tests when that input is permitted.
06 | WALK THROUGH A LIST DIRECTLY
names = ["Ada", "Lin", "Sam"]
for name in names:
print("Hello", name)
On each iteration, name receives the next list value. The outputs are Hello Ada, Hello Lin and Hello Sam. This is often clearer than maintaining an index when the objective only needs values.
If position is also useful, Python enumerate can supply it: for position, name in enumerate(names, start=1). The displayed position then starts at 1, while the underlying list indexes still start at 0.
Avoid changing the collection’s size while directly iterating over it unless you deliberately understand the consequences. Build a new collection or use a suitable separate update strategy.
07 | WHILE: REPEAT WHILE A CONDITION IS TRUE
remaining = 3
while remaining > 0:
print("Remaining:", remaining)
remaining = remaining - 1
print("Complete")
A while loop tests its condition before entering its body and again before every later iteration. It prints 3, 2 and 1. The update then makes remaining 0, so the next test is false and execution continues with Complete.
The three jobs are initialization, condition and progress. Initialization establishes the starting state. The condition decides whether another iteration may begin. The body must eventually change relevant state or respond to an external change so the condition can become false.
08 | TRACE THE FINAL FALSE TEST
| Stage | remaining before test | remaining > 0 | Action |
|---|---|---|---|
| First test | 3 | True | Print 3; update to 2 |
| Second test | 2 | True | Print 2; update to 1 |
| Third test | 1 | True | Print 1; update to 0 |
| Fourth test | 0 | False | Skip body; print Complete afterwards |
There are three body executions but four condition tests in this normally terminating while loop. The final false test is part of the trace even though it produces no new body output.
A variable shown at the start of an iteration can differ from its value at the end. Label trace columns carefully rather than placing both values in an unexplained cell.
09 | INTERACTIVE: WATCH THE BODY CHANGE STATE
Select a supplied program and choose a whole-number limit from 0 to 10. Step through its checks and body executions. The activity shows state after each action and includes the final failed check; it models these supplied programs rather than running arbitrary code.
10 | CHOOSE THE LOOP FROM THE REQUIREMENT
| Requirement | Suitable approach | Why |
|---|---|---|
| Print five labels | for with range | Known count |
| Visit every stored name | for over list | Each existing item |
| Ask until valid input | while | Unknown number of attempts |
| Read until a stop marker | while / sentinel | Data determines end |
| Process each row and column | Nested loops | Repeated work within repeated work |
A for loop often communicates a known sequence clearly. A while loop makes an evolving condition explicit. Both can sometimes solve the same problem, but clarity of control matters.
A correct choice includes a correct initialization, body and end rule. Merely naming for or while does not construct the required solution.
11 | TOTAL: KEEP THE OLD VALUE AND ADD THE NEW ONE
scores = [8, 5, 7]
total = 0
for score in scores:
total = total + score
print("Total:", total)
total starts at 0 because no scores have been included yet. The assignment total = total + score reads the old total on the right, adds the current score, and replaces total with the result. It does not claim the two sides were already equal.
The successive calculations are 0 + 8 = 8, then 8 + 5 = 13, then 13 + 7 = 20. Earlier scores stay included because each new calculation starts with the accumulated value.
Initialize total before the loop. Resetting it to 0 inside every iteration would discard the previous running total. Output the final result after the loop when only the completed total is required.
12 | COUNT MATCHES WITH A SELECTION INSIDE THE LOOP
scores = [8, 5, 7]
passes = 0
for score in scores:
if score >= 6:
passes = passes + 1
print("Passes:", passes)
The loop visits all three scores, but the inner if increments passes only for 8 and 7. The final count is 2. The body is the whole indented block, including the selection.
A count increases by 1 for each matching item. A total increases by the value being accumulated. Mixing these updates can produce a plausible but incorrect answer.
13 | SENTINELS: LET A SPECIAL VALUE END INPUT
total = 0
raw = input("Enter a whole number, or stop: ")
while raw != "stop":
total = total + int(raw)
raw = input("Enter a whole number, or stop: ")
print("Total:", total)
A sentinel is a special value that signals the end of input. Here the exact word stop is the sentinel. It is tested before conversion, so the program never tries int("stop"). The first input primes the loop; the later input allows the condition to change.
This introductory version assumes each non-sentinel input is a valid whole number and uses lowercase stop. If stop is entered immediately, the body runs zero times and the total is 0. A complete user-facing version should also handle invalid text.
Choose a marker outside the valid data values. Using 0 as the sentinel would prevent 0 from being processed as ordinary data under this design.
14 | VALIDATION NEEDS ANOTHER OPPORTUNITY TO CHANGE
while True:
raw = input("Enter a mark from 0 to 100: ")
try:
mark = int(raw)
except ValueError:
print("Use a whole number")
continue
if 0 <= mark <= 100:
break
print("Outside the allowed range")
print("Accepted:", mark)
while True deliberately repeats until an explicit break. A valid converted mark reaches break. Invalid numeric range prints feedback and repeats; invalid text reaches continue and starts the next iteration.
The input is inside the loop, so each new attempt supplies fresh data. Testing the same unchanged invalid value forever would not create a useful validation loop.
This example assumes interactive input remains available. Handling end-of-input or user cancellation is a separate requirement.
15 | BREAK AND CONTINUE HAVE DIFFERENT JOBS
break exits the nearest enclosing loop immediately. continue skips the remaining body instructions for the current iteration and proceeds with that loop’s next iteration. Neither means “exit the whole program”.
for number in [2, -1, 4, 0, 9]:
if number < 0:
continue
if number == 0:
break
print(number)
print("Done")
The outputs are 2, 4 and Done. Negative -1 is skipped. Zero ends the loop, so 9 is never visited.
With a while loop, continue can accidentally skip a necessary counter update. Place progress where every continuing route reaches it, or restructure the logic.
16 | PRE-CONDITION AND POST-CONDITION LOOPS
A pre-condition loop checks before the body, so it may execute zero times. Python while is pre-condition. A post-condition loop checks after the body and therefore executes at least once when reached normally.
Python has no built-in do/while statement. A while True loop with a conditional break at the end can express a post-condition pattern. Java provides do/while directly.
In a do/while, a true condition means continue. In pseudocode REPEAT UNTIL, a true stopping condition means stop. Do not copy the same condition without considering this reversed meaning.
attempt = 0
while True:
attempt = attempt + 1
print("Attempt", attempt)
if attempt >= 3:
break
17 | JAVA: COUNT WITH FOR
public class CountExample {
public static void main(String[] args) {
for (int number = 1; number <= 3; number++) {
System.out.println(number);
}
System.out.println("Finished");
}
}
The header contains initialization, condition and update. int number = 1 runs once. number <= 3 is tested before each body execution. number++ increments after each completed body execution, before the next test.
The outputs are 1, 2, 3 and Finished. Unlike range’s excluded stop, this explicit <= condition includes 3. Braces identify the Java body; indentation should reflect them.
18 | JAVA: WHILE AND DO/WHILE
public class ConditionExample {
public static void main(String[] args) {
int remaining = 0;
while (remaining > 0) {
System.out.println("While body");
remaining--;
}
int attempt = 0;
do {
attempt++;
System.out.println("Attempt " + attempt);
} while (attempt < 3);
}
}
The while body executes zero times because remaining is already 0. The do body executes three times, producing Attempt 1, Attempt 2 and Attempt 3. Java’s do/while ends with a semicolon after its condition.
A semicolon accidentally placed immediately after a normal while header can instead create an empty loop body. Read the actual structure when debugging.
19 | NESTED LOOPS: COMPLETE THE INNER LOOP EACH TIME
for row in range(1, 3):
for column in range(1, 4):
print("Row", row, "column", column)
The inner loop is inside the outer body. For row 1, column visits 1, 2, 3. Only then does row become 2, when a new inner loop again visits 1, 2, 3. There are 2 × 3 = 6 prints.
The two loop variables do not increase together on each print. The inner variable restarts because its for statement is reached again for each outer iteration.
For fixed independent counts, multiply the counts. If the inner bounds depend on the outer variable, count each outer iteration separately instead of assuming a simple rectangle.
20 | NESTED TRACE: A SMALL SEATING PLAN
| Print number | row | column |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 3 |
Think of numbering seats across one row before moving to the next. The row value remains unchanged while the inner loop visits that row’s columns.
In nested loops, break exits only the innermost loop containing it. If an objective requires leaving both loops, use an explicitly designed flag, a suitable function return or another clear structure.
21 | PROCESS A TWO-DIMENSIONAL COLLECTION
grid = [[4, 7, 2], [5, 1, 6]]
grand_total = 0
for row in grid:
row_total = 0
for value in row:
row_total = row_total + value
grand_total = grand_total + value
print("Row total:", row_total)
print("Grand total:", grand_total)
The row totals are 13 and 12; the grand total is 25. row_total is reset once per outer iteration because each row needs its own total. grand_total is initialized once before both loops because it must retain values across rows.
The placement of initialization expresses what the accumulator covers. Putting grand_total = 0 inside the outer body would discard earlier rows.
22 | INFINITE LOOPS AND OFF-BY-ONE ERRORS
number = 1
while number <= 3:
print(number)
number = number + 1
Removing the update leaves number at 1 forever in this isolated example. Changing it to number = number - 1 moves away from termination. An intentional event loop can run indefinitely by design, but an accidental loop that cannot meet its objective is a logic error.
An off-by-one error performs one repetition too many or too few. For inclusive 1 to 3, number < 3 incorrectly omits 3. For Python range, range(1, 3) also omits 3; use range(1, 4).
Check the first state, last included state and first excluded state, as well as whether every continuing route makes progress.
23 | WORKED SOLUTION: COUNT, TOTAL AND AVERAGE
scores = [8, 5, 7]
total = 0
count = 0
for score in scores:
total = total + score
count = count + 1
if count > 0:
average = total / count
print("Average:", average)
else:
print("No scores")
The average is 20 / 3. Both accumulators start outside the loop. The final selection prevents division by zero for an empty list.
Although len(scores) and sum(scores) could simplify this particular Python task, constructing the loop makes the algorithm visible and transfers to streamed input or additional per-item processing.
Test the empty case as well as several scores. A program that works for three positive values may still fail when no values are supplied.
24 | CONSTRUCT IT: A LIMITED SEARCH
Given names = ["Ada", "Lin", "Sam"], find whether "Lin" is present. Stop visiting names once a match is found, and print exactly one final message. First identify the initial state and the condition that changes it.
names = ["Ada", "Lin", "Sam"]
target = "Lin"
found = False
for name in names:
if name == target:
found = True
break
if found:
print("Found")
else:
print("Not found")
found records the result across the loop. The message is after the loop so earlier nonmatches do not incorrectly print Not found. With duplicate matches, this solution stops at the first.
Try a target at the first position, the last position, an absent target and an empty list. Decide whether the objective wants a Boolean, an index, a count or every match before constructing the body.
25 | TEST THE CONTROL, NOT JUST THE FINAL NUMBER
| Test | What to inspect |
|---|---|
| Zero iterations where allowed | Body skipped; initial/final state sensible |
| One iteration | Initialization and first update |
| Several iterations | State carried across repetitions |
| Last permitted value | Inclusive/exclusive boundary |
| Sentinel entered first | Marker excluded; empty-data result |
| Invalid input then valid | Fresh input and progress after error |
| Nested rows/columns | Inner loop restarts; correct totals |
Trace condition results, body actions and relevant variable values. Expected output should be calculated before running the program. Then compare actual output and inspect the first point where the trace diverges.
Never test a suspected accidental infinite loop by leaving it running without control. Inspect the update path and use a debugger or bounded diagnostic run.
26 | BUILD A LOOP WITH A CLEAR CONTRACT
Start by stating what must repeat and what result must exist afterwards. Choose the items or condition, initialize state outside the appropriate loop, and write the body with a clear progress rule. Place final reporting after repetition when it should happen once.
Then trace zero, one and several iterations, plus the boundary that stops the loop. For nested loops, explain what remains fixed during the inner loop and what resets when a new outer iteration starts.
A strong constructed solution meets the objective for the whole allowed input range, rather than only reproducing one sample output.