3.1 The for Loop & range()
A for loop is count-controlled — it runs a fixed number of times, known before the loop starts. It maps directly from pseudocode FOR i ← 1 TO n ... NEXT i.
# Basic syntax — loops over a sequence
for variable in sequence:
# code runs once per item
# range(5) → 0 to 4
for i in range(5):
print(i)
# Output: 0 1 2 3 4
# range(1, 6) → 1 to 5
for i in range(1, 6):
print(i)
# range(0, 10, 2) → even numbers
for i in range(0, 10, 2):
print(i)
# Output: 0 2 4 6 8range(1, 11)gives 1 through 10 — the stop value (11) is never included.- The pseudocode
FOR i ← 1 TO 10includes 10, so always add 1 to the stop value when translating. FOR i ← 1 TO 10→for i in range(1, 11).
| range() call | Produces | Count |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | 5 |
range(1, 6) | 1, 2, 3, 4, 5 | 5 |
range(0, 10, 2) | 0, 2, 4, 6, 8 | 5 |
range(1, 11) | 1, 2, 3, …, 10 | 10 |
- Initialise total = 0 before the loop
- Use range(1, 6) to loop 5 times
- Add each score to total inside the loop
The for Loop & range()
3.2 Iterating over Lists & Strings
A for loop can step through every item in a list or every character in a string directly — no index needed.
Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
# Summing a list
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(total) # 150Iterating over a string
for char in "Python":
print(char)
# P y t h o n (each on a new line)
# Count vowels
word = "programming"
vowels = "aeiou"
count = 0
for char in word:
if char in vowels:
count += 1
print(count) # 3- When summing or counting with a for loop, initialise the accumulator (
total = 0orcount = 0) before the loop. - Then update it inside the loop body.
Iterating over Lists & Strings
3.3 Nested for Loops
A nested loop is a loop inside another loop. For every single iteration of the outer loop, the inner loop runs its full sequence. Used for multiplication tables, 2D grids and processing 2D arrays.
# Nested loop — i is outer, j is inner
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
# i=1,j=1 i=1,j=2 i=1,j=3
# i=2,j=1 i=2,j=2 i=2,j=3
# i=3,j=1 i=3,j=2 i=3,j=3
# Multiplication table 1×1 through 3×3
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")- If the outer loop runs
mtimes and the inner runsntimes, the inner body runs m × n times total. - For 3 × 4 that is 12 iterations.
Nested for Loops
3.4 The while Loop
A while loop is condition-controlled — it keeps running as long as its condition is True, and stops the moment it becomes False. The number of iterations is not known in advance. It maps from pseudocode WHILE condition DO ... ENDWHILE.
# Pseudocode: WHILE x <= 5 DO ... ENDWHILE
x = 1
while x <= 5:
print(x)
x += 1
# Output: 1 2 3 4 5- Inside a
whileloop you must change the variable that the condition checks. - If you forget
x += 1, the condition staysTrueforever — an infinite loop. - Cambridge will not award marks for code with an obvious infinite loop unless one was specifically requested.
- Read the first attempt before the loop
- Loop while the input is invalid
- Re-read inside the loop
- Use a while loop that checks the password
- Condition is password != "python123"
- Input validation loops are a very common Paper 4 question type.
- Cambridge expects you to read the input before the loop, then re-read it inside the loop.
- If you only read inside, the first value is never validated — this loses the mark for correct loop structure.
Countdown & sentinel loop
# Countdown timer
count = 10
while count > 0:
print(count)
count -= 1
print("Blast off!")
# Sentinel loop — stop on -1
total = 0
number = int(input("Enter number (-1 to stop): "))
while number != -1:
total += number
number = int(input("Enter number (-1 to stop): "))
print(f"Total: {total}")The while Loop
3.5 break & continue
break and continue give fine-grained control over a loop without needing extra Boolean flags. break is often used in search loops (stop when found); continue in filtering loops (skip items that do not match).
break — exit the loop early
# break in a for loop
for i in range(1, 11):
if i == 7:
break
print(i)
# Output: 1 2 3 4 5 6
# Search list — stop when found
numbers = [1, 2, 3, 5, 8, 13]
for num in numbers:
if num == 5:
print("Found!")
breakcontinue — skip this iteration
# Skip number 5
for i in range(1, 11):
if i == 5:
continue
print(i)
# Output: 1 2 3 4 6 7 8 9 10
# Print only odd numbers
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
# Output: 1 3 5 7 9- When using
continuein awhileloop, make sure you increment the loop variable before the continue. - Otherwise the variable never changes and you get an infinite loop.
- break on zero exits the loop entirely
- continue skips the print for negatives but does not exit
- Valid positive numbers fall through to the final print
- Use a for loop with range(1, 9)
- Check for -999 first → break
- Check for invalid range → continue
- Count valid marks with a counter variable
break & continue
3.6 for vs while — Choosing the Right Loop
Cambridge Paper 4 questions describe a scenario and expect you to pick the correct loop type. Choosing the wrong loop does not always crash, but it produces incorrect structure — and the mark scheme specifies which loop is expected based on the pseudocode construct.
| Aspect | for loop | while loop |
|---|---|---|
| When to use | Iterations known in advance | Iterations unknown — only stopping condition |
| Pseudocode | FOR i ← 1 TO n ... NEXT i | WHILE cond DO ... ENDWHILE |
| Use cases | Accumulator over n values, iterating a list, char processing | Input validation, password checks, sentinel loops, menus |
| Risk of infinite loop | No (range is fixed) | Yes — if the condition never becomes False |
| Signal words | "for each", "repeat 10 times", "process every item" | "until valid", "keep asking", "while not correct" |
- Quick decision rule: If the question gives a fixed number (
30 students,10 numbers), use aforloop. - If it describes a condition (
until valid,while not correct), use awhileloop.
- (a) Use for — fixed count of 30
- (b) Use while — unknown repetitions until valid input
- (a) You know it runs exactly 12 times
- (b) You do not know how many tries the user needs
for vs while & Input Validation
3.7 Exam Focus & Lab Tasks
Common mistakes that lose marks
| Mistake | What happens | Fix |
|---|---|---|
range(1, 10) for "1 to 10 inclusive" | Loop runs 9 times, misses 10 | range(1, 11) — stop is exclusive |
| Forgetting to increment in while loop | Infinite loop | x += 1 inside the loop body |
| Reading input only inside validation loop | First value never checked | Read before the loop, re-read inside |
| Calculating average inside the loop | Wrong intermediate results each iteration | Calculate average AFTER the loop ends |
continue in while without updating first | Infinite loop — variable never changes | Increment before continue |
| Using for for unknown count (password retry) | Loop ends before user succeeds | Use while for condition-controlled tasks |
Exam-style Lab Tasks
3.8 Practice Tasks
Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.
✓ Key Points Summary
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
What does range(1, 6) produce?
Question 2True / False
A for loop is count-controlled and runs a fixed number of times known in advance.
Question 3Multiple Choice
Pseudocode "FOR i ← 1 TO 10" maps to which Python line?
Question 4Multiple Choice
Which loop type should you use to keep asking for a password until it is correct?
Question 5True / False
Forgetting to update the loop variable in a while loop causes an infinite loop.
Question 6Multiple Choice
What does the break statement do?
Question 7Multiple Choice
What is the output of: for i in range(1, 6): if i == 3: continue print(i)
Question 8True / False
In a nested for loop, the inner loop runs to completion once per outer iteration.
Question 9Multiple Choice
How many times does the inner body run if outer is range(3) and inner is range(4)?
Question 10Multiple Choice
In input validation, why must you read input BEFORE the while loop?
Question 11True / False
range(0, 10, 2) produces 0, 2, 4, 6, 8, 10.
Question 12Multiple Choice
Which common mistake loses marks when calculating an average in a loop?
Answer all 12 questions to enable submission.