Python Foundations

Iteration

Repeating code with FOR, WHILE and condition-controlled loops — range(), iterating over lists and strings, nested loops, break, continue, and how to choose the right loop for each Paper 4 task.

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 8
Key rule — range() stop value is exclusive:
  • range(1, 11) gives 1 through 10 — the stop value (11) is never included.
  • The pseudocode FOR i ← 1 TO 10 includes 10, so always add 1 to the stop value when translating.
  • FOR i ← 1 TO 10for i in range(1, 11).
range() callProducesCount
range(5)0, 1, 2, 3, 45
range(1, 6)1, 2, 3, 4, 55
range(0, 10, 2)0, 2, 4, 6, 85
range(1, 11)1, 2, 3, …, 1010
Task
Write a program that prints all numbers from 1 to 10 using a for loop and range(). Then write a second loop that prints the first 10 multiples of 5 (5, 10, 15, …, 50).
Your Turn — for loop with accumulator [5 marks]
Write a Python program that reads 5 integer scores from the user, calculates the total and the average, and outputs both.
Hint:
  • Initialise total = 0 before the loop
  • Use range(1, 6) to loop 5 times
  • Add each score to total inside the loop

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)  # 150

Iterating 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
Accumulator pattern:
  • When summing or counting with a for loop, initialise the accumulator (total = 0 or count = 0) before the loop.
  • Then update it inside the loop body.
Task
Create a list of 5 cities. Write a program that prints each city on a separate line. Then write a second program to calculate the sum of all values in the list [15, 25, 35, 45, 55].
Task
Write a program that prints each character of the string "Bangladesh" on a new line. Then write a program that counts the vowels in any string entered by the user.

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}")
Exam tip:
  • If the outer loop runs m times and the inner runs n times, the inner body runs m × n times total.
  • For 3 × 4 that is 12 iterations.
Task
Write a program to generate and print the full multiplication table for numbers 1 to 5 (i.e., 1×1 through 5×5). Each line should read: 2 x 3 = 6

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
Key rule — always update the loop variable:
  • Inside a while loop you must change the variable that the condition checks.
  • If you forget x += 1, the condition stays True forever — an infinite loop.
  • Cambridge will not award marks for code with an obvious infinite loop unless one was specifically requested.
Task
Write a program using a while loop to print all numbers from 1 to 20. Then write a second program to print the first 10 multiples of 3.
Your Turn — while loop for input validation [4 marks]
Write a Python program that asks the user for a number between 1 and 10 (inclusive). Keep asking until they enter a valid number, then print it.
Hint:
  • Read the first attempt before the loop
  • Loop while the input is invalid
  • Re-read inside the loop
Your Turn [4 marks]
Write a Python program that keeps asking the user for a password until they type "python123". Once correct, print "Access granted!"
Hint:
  • Use a while loop that checks the password
  • Condition is password != "python123"
Exam tip:
  • 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}")
Task
Write a program that counts down from 10 to 1 and then prints "Happy New Year!" Then write a sentinel loop that keeps reading positive numbers from the user until they enter 0, and prints the total.

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!")
        break

continue — 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
Task
Write a program that asks the user for numbers one at a time. Stop and print "Negative number entered!" as soon as the user enters a negative number.
Task
Write a program that asks the user repeatedly for a secret word. If they type "quit", print "Goodbye!" and stop. Otherwise print "Keep trying!"
Task
Write a program that prints all numbers from 1 to 20 except multiples of 3. Use continue to skip them.
Task
Write a while loop that counts from 1 to 15 but skips printing any number that is divisible by 4.
Exam tip — continue in a while loop:
  • When using continue in a while loop, make sure you increment the loop variable before the continue.
  • Otherwise the variable never changes and you get an infinite loop.
Your Turn — break and continue in a search program [6 marks]
A program reads a list of 10 numbers entered by the user. It should skip any negative number (print a warning and continue), and stop entirely if the user enters 0. Print each valid positive number as it is entered.
Hint:
  • 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
Your Turn [6 marks]
Write a program that reads up to 8 student marks. Skip any mark below 0 or above 100 (invalid — print a warning and continue). If the user enters -999, stop early. Count and print how many valid marks were processed.
Hint:
  • 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

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.

Aspectfor loopwhile loop
When to useIterations known in advanceIterations unknown — only stopping condition
PseudocodeFOR i ← 1 TO n ... NEXT iWHILE cond DO ... ENDWHILE
Use casesAccumulator over n values, iterating a list, char processingInput validation, password checks, sentinel loops, menus
Risk of infinite loopNo (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"
Exam tip:
  • Quick decision rule: If the question gives a fixed number (30 students, 10 numbers), use a for loop.
  • If it describes a condition (until valid, while not correct), use a while loop.
Your Turn — Selecting the correct loop type [4 marks]
A school system needs two routines: (a) Read exactly 30 student names into a list. (b) Keep asking for a PIN until the user enters a 4-digit number. Write both.
Hint:
  • (a) Use for — fixed count of 30
  • (b) Use while — unknown repetitions until valid input
Your Turn [4 marks]
Decide which loop to use and write the code for each scenario: (a) Print a times table for a number entered by the user, from 1 to 12. (b) Keep asking the user for an age until they enter a value between 0 and 120.
Hint:
  • (a) You know it runs exactly 12 times
  • (b) You do not know how many tries the user needs

3.7 Exam Focus & Lab Tasks

Common mistakes that lose marks

MistakeWhat happensFix
range(1, 10) for "1 to 10 inclusive"Loop runs 9 times, misses 10range(1, 11) — stop is exclusive
Forgetting to increment in while loopInfinite loopx += 1 inside the loop body
Reading input only inside validation loopFirst value never checkedRead before the loop, re-read inside
Calculating average inside the loopWrong intermediate results each iterationCalculate average AFTER the loop ends
continue in while without updating firstInfinite loop — variable never changesIncrement before continue
Using for for unknown count (password retry)Loop ends before user succeedsUse while for condition-controlled tasks

Exam-style Lab Tasks

Lab Task — 1 — Number Guessing Game
Set a secret number (e.g. 42). Use a while loop to keep asking the user to guess. Print "Too low", "Too high", or "Correct! You took X guesses." Count the guesses with a counter variable.
Lab Task — 2 — Sales Report
Read 7 daily sales figures (float) using a for loop. Calculate total and average sales. Print the highest and lowest single day. Print how many days exceeded the average.
Lab Task — 3 — FizzBuzz with Loop
Use a for loop from 1 to 100. Multiples of 3 and 5 → FizzBuzz. Multiples of 3 only → Fizz. Multiples of 5 only → Buzz. Otherwise print the number.
Lab Task — 4 — PIN Entry System
Allow up to 3 attempts to enter the correct PIN ("1234"). Use a for loop for the attempt count. Use break if correct PIN entered. After the loop, check if they succeeded or ran out of attempts.
Lab Task — 5 — Prime Number Checker
Ask the user for a number greater than 1. Use a for loop to check if it has any divisors between 2 and number−1. Use break when a divisor is found. Print "Prime" or "Not prime" with the lowest divisor if not prime.

3.8 Practice Tasks

Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.

1Practice Task — FOR loop with range [2 marks]
Write a Python for loop that prints the numbers 1 to 10 inclusive, each on a new line.
2Practice Task — WHILE loop basics [2 marks]
Write a while loop that counts down from 5 to 1, printing each number, then prints "Blast off!" after the loop ends.
3Practice Task — Loop counting [2 marks]
How many times will the following loop body execute? Explain your answer. for i in range(2, 20, 3): print(i)
4Practice Task — Accumulating totals [3 marks]
Use a for loop to calculate and print the sum of all integers from 1 to 10 (inclusive).
5Practice Task — Factorial with loop [3 marks]
Write a Python program using a for loop to calculate the factorial of 5 (i.e. 5! = 5 x 4 x 3 x 2 x 1). Print the result.
6Practice Task — REPEAT...UNTIL translation [3 marks]
The following pseudocode uses REPEAT...UNTIL. Translate it to Python using a while loop. x <- 0 REPEAT x <- x + 1 PRINT x UNTIL x >= 5
7Practice Task — Finding max with a loop [4 marks]
Given the list nums = [3, 18, 7, 25, 9, 14], write a for loop to find and print the largest value. Do NOT use the built-in max() function.
8Practice Task — Finding min with a loop [4 marks]
Given the list nums = [3, 18, 7, 25, 9, 14], write a for loop to find and print the smallest value. Do NOT use the built-in min() function.
9Practice Task — Nested loops — multiplication table [4 marks]
Use two nested for loops to print a 5x5 multiplication table. Each row should show the products 1xn, 2xn, ... 5xn separated by a tab.
10Practice Task — Star pattern — right triangle [4 marks]
Use a nested for loop to print a right-angled triangle of stars, 5 rows high: * ** *** **** *****
11Practice Task — Number pattern — pyramid [5 marks]
Use nested for loops to print the following number pattern: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
12Practice Task — Table of squares [3 marks]
Use a for loop to print a table of squares for numbers 1 to 5. Each row should show the number and its square, separated by spaces. Include a header row.
13Practice Task — Sum of digits [5 marks]
Write a Python program that asks the user for a positive integer and uses a while loop to calculate the sum of its digits. Example: input 1234 should output 10 (1+2+3+4).
14Practice Task — Countdown timer with break/continue [6 marks]
Write a countdown timer that starts at 10. Use a while loop to count down to 0. Skip printing the number 7 (use continue). If the user types "stop" at any prompt, break out of the loop early. Otherwise print each number with a 1-second pause (use import time; time.sleep(1)).
15Practice Task — Full exam-style iteration question [8 marks]
A teacher wants to analyse test scores. Write a complete Python program that: 1. Asks the user how many students there are. 2. Uses a for loop to read each score (0 to 100). 3. Uses a while loop to validate each score is between 0 and 100 (re-prompt if invalid). 4. After all scores are entered, calculates and prints: the total, the average, the highest score, and how many students scored above the average. 5. Do NOT use built-in sum(), max() or min() functions.

Key Points Summary

for loop = count-controlled (known iterations); while loop = condition-controlled (unknown).
range(stop) is EXCLUSIVE — range(1, 11) gives 1..10, matching pseudocode FOR i ← 1 TO 10.
range(start, stop, step) — e.g. range(0, 10, 2) → 0, 2, 4, 6, 8.
for fruit in list / for char in string — iterate items directly, no index needed.
Accumulators (total, count) must be initialised BEFORE the loop and updated INSIDE it.
Nested for loop: inner runs fully per outer iteration → m × n total inner-body runs.
while loop MUST update its condition variable inside the body — otherwise infinite loop.
Input validation: read BEFORE the loop, re-read INSIDE the loop, confirm AFTER.
break exits the loop entirely; continue skips to the next iteration.
In a while + continue, increment the variable BEFORE continue to avoid infinite loops.

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

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.