Topic 8 · Programming
Iteration: FOR, WHILE and REPEAT loops
Iteration means repeating a set of instructions. It's what makes computers useful: they never get bored doing the same thing a million times.
There are three kinds of loop. In the exam you must write them in pseudocode; in real programs you'll use Python. This lesson shows both side by side.
1. Count-controlled loop: FOR
Use it when you know how many times to repeat before the loop starts.
FOR Count ← 1 TO 5
OUTPUT Count * Count
NEXT Count
for count in range(1, 6):
print(count * count)
Both print 1, 4, 9, 16, 25. Watch out: Python's range(1, 6) stops before 6.
You can count in steps, and backwards:
FOR Count ← 10 TO 0 STEP -2
OUTPUT Count
NEXT Count
2. Pre-condition loop: WHILE
The condition is checked before each repeat. If it's FALSE at the start, the loop body never runs.
Total ← 0
INPUT Number
WHILE Number <> -1 DO
Total ← Total + Number
INPUT Number
ENDWHILE
OUTPUT Total
total = 0
number = int(input())
while number != -1:
total = total + number
number = int(input())
print(total)
This keeps adding numbers until the user types −1 (a rogue value that means "stop").
3. Post-condition loop: REPEAT … UNTIL
The condition is checked after each repeat, so the body always runs at least once. The loop stops when the condition becomes TRUE.
REPEAT
OUTPUT "Enter your PIN"
INPUT PIN
UNTIL PIN = 1234
Python has no REPEAT … UNTIL, so we use while True: with break:
while True:
pin = int(input("Enter your PIN: "))
if pin == 1234:
break
Which loop should I use?
| Situation | Loop |
|---|---|
| You know the number of repeats (e.g. 30 students) | FOR |
| It might need to run zero times | WHILE |
| It must run at least once (e.g. asking for input until it's valid) | REPEAT … UNTIL |
WHILE repeats while the condition is TRUE. UNTIL repeats until the condition is TRUE. They're opposites, so the condition flips when you swap one for the other.
Key terms
| Term | Meaning |
|---|---|
| Iteration | Repeating a set of statements |
| Count-controlled loop | Repeats a fixed number of times (FOR) |
| Pre-condition loop | Tests its condition before each repeat (WHILE) |
| Post-condition loop | Tests its condition after each repeat (REPEAT … UNTIL) |
| Rogue value | A special input value that tells a loop to stop |
Coding exercise · Python
Count down
Read a whole number n (1 to 20). Print the numbers from n down to 1, one per line, then print Lift off!.
Input for “Run” (one value per line)
Coding exercise · Python
Keep asking until it's valid
Keep reading marks until you get one between 0 and 100 (inclusive). Each time a mark is out of range, print Invalid. When a valid mark arrives, print Accepted: followed by the mark.
This is a post-condition loop problem: you always need to read at least one mark.
Input for “Run” (one value per line)
Quiz
Quick check: loops
6 questions