Why Does This Matter?
Imagine your teacher tells you to write "I will not talk in class" 100 times. Would you write it out line by line? Of course not — you would want to repeat it automatically. That is exactly what loops do in programming.
Loops let you repeat actions without writing the same code over and over. Instead of copying and pasting a line of code 100 times, you write a loop that says "do this 100 times" — and the computer handles the rest.
You already experience loops every day without thinking about it. A music playlist on repeat plays each song one after another, then starts again. A factory assembly line performs the same steps on every item. Your daily routine — wake up, brush teeth, eat breakfast — repeats every single morning. Programming loops work in exactly the same way.
Loops are one of the most fundamental concepts in all of computer science. Almost every useful program ever written contains at least one loop. Without loops, computers would be little more than expensive calculators — unable to process large amounts of data, unable to keep games running, and unable to display your social media feed.
By the end of this chapter, you will be able to:
- Use
forloops withrange()to repeat actions a set number of times - Use
forloops to iterate through lists and strings - Use
whileloops to repeat actions based on a condition - Explain the difference between count-controlled and condition-controlled loops
- Use the accumulator pattern to build up totals and results
- Write nested loops (loops inside loops)
- Avoid infinite loops and understand why they happen
- Use
breakandcontinueto control the flow of a loop - Complete a trace table to track variables through a loop
See It in Action
The best way to understand loops is to run some code and experiment. Try each example below, then change the values to see what happens. Do not be afraid to break things — that is how you learn!
Example 1: For Loop with range()
This program counts from 1 to 5 and prints each number. The for loop automatically moves through each value in the range.
range(1, 6). How many numbers will it print? Will it include 6? Careful — this is a common exam trap!
2
3
4
5
range(1, 6) goes from 1 up to but NOT including 6. So it prints 5 numbers. The stop value is always excluded.
# Counting from 1 to 5 using a for loop
for number in range(1, 6):
print(number)
range(1, 6) to range(1, 11) to count up to 10. What happens if you use range(5) instead — what number does it start from?
Example 2: For Loop with a List
You can also loop through a list of items. Here we print each fruit from a list, one at a time.
# Looping through a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like " + fruit)
"mango" and "grape". Can you also loop through a list of your friends' names instead?
Example 3: While Loop — Countdown
A while loop keeps running as long as its condition is True. This program counts down from 5 to 1, then prints "Blast off!"
countdown starts at 5. Each time around the loop, it decreases by 1. How many times will the loop body run? Will "Blast off!" appear inside or outside the loop?
4
3
2
1
Blast off!
The loop runs 5 times (while countdown > 0). "Blast off!" is OUTSIDE the loop (not indented), so it runs once after the loop finishes.
# Countdown using a while loop
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Blast off!")
countdown = countdown - 1? (Think about it — but be careful running it!)
Example 4: Nested Loops — Multiplication Table
You can put a loop inside another loop. This is called a nested loop. The inner loop runs completely for every single iteration of the outer loop. Here we use two for loops to build a 5×5 multiplication table.
# Multiplication table using nested loops
for row in range(1, 6):
line = ""
for col in range(1, 6):
result = row * col
line = line + str(result) + "\t"
print(line)
range(1, 6) to range(1, 13) to build a full 12×12 times table. Can you add a header row showing the column numbers?
Example 5: Looping Through Strings
In Python, a string is a sequence of characters. That means you can loop through each character one at a time, just like you loop through items in a list. This is incredibly useful for tasks like checking passwords, counting letters, or encoding messages.
# Looping through each character in a word
word = "Python"
for letter in word:
print(letter, "- ASCII code:", ord(letter))
letter.lower() in "aeiou".)
Example 6: The Accumulator Pattern
One of the most common loop patterns is the accumulator — you start with a value (usually 0) and build it up each time around the loop. Legend has it that the mathematician Carl Friedrich Gauss calculated the sum of 1 to 100 in his head as a child. Let us get Python to do it for us.
# Accumulator pattern: sum of 1 to 100
total = 0
for number in range(1, 101):
total = total + number
print("The sum of 1 to 100 is:", total)
Example 7: While Loop with Validation
A very common use of while loops is input validation — repeating a question until the user gives an acceptable answer. This simulates a password check with a maximum of 3 attempts. (Since we cannot use input() in the browser, we simulate the attempts with a list.)
# Password check with maximum 3 attempts
password = "secret123"
attempts = 0
max_attempts = 3
logged_in = False
# Simulating user guesses (in a real program, you would use input())
guesses = ["hello", "password", "secret123"]
while attempts < max_attempts and not logged_in:
guess = guesses[attempts]
attempts = attempts + 1
print("Attempt " + str(attempts) + ": Entered '" + guess + "'")
if guess == password:
logged_in = True
print("Access granted!")
else:
remaining = max_attempts - attempts
if remaining > 0:
print("Wrong password. " + str(remaining) + " attempts remaining.\n")
if not logged_in:
print("Account locked. Too many failed attempts.")
max_attempts to 5 and adding more guesses.
How Does It Work?
For Loops: Iterating Over a Sequence
A for loop goes through each item in a sequence — one at a time. A sequence can be a range(), a list, or even a string (where each character is an item).
The basic structure is:
# Structure of a for loop
for item in sequence:
# do something with item
print(item)
# Example: looping through each letter in a word
for letter in "Python":
print(letter)
Each time around the loop is called an iteration. The loop variable (like item or letter) automatically takes on the next value in the sequence with each iteration. You do not need to update it yourself — Python handles that for you.
The range() Function
The range() function generates a sequence of numbers. It is one of the most useful tools for for loops. There are three ways to use it:
| Syntax | What It Produces | Example |
|---|---|---|
range(5) |
0, 1, 2, 3, 4 | Five numbers starting from 0 |
range(1, 6) |
1, 2, 3, 4, 5 | Start at 1, stop before 6 |
range(0, 10, 2) |
0, 2, 4, 6, 8 | Start at 0, stop before 10, step by 2 |
range(10, 0, -1) |
10, 9, 8, 7, 6, 5, 4, 3, 2, 1 | Count backwards from 10 to 1 |
Notice that range() always stops before the end number. This catches many beginners out — if you want to count from 1 to 10, you need range(1, 11), not range(1, 10).
range() function does not actually create a list of numbers in memory. Instead, it generates each number on demand as the loop needs it. This is called lazy evaluation, and it makes range() incredibly memory-efficient. You could write range(1, 1000000000) and Python would not try to store a billion numbers in memory — it would just produce them one at a time.
While Loops: Repeat While a Condition is True
A while loop keeps repeating as long as its condition remains True. You must make sure the condition eventually becomes False, or the loop will never stop.
The basic structure is:
# Structure of a while loop
count = 1
while count <= 5:
print("Count is:", count)
count = count + 1
print("Loop finished!")
Notice the three essential parts of a while loop:
- Initialise the variable before the loop (
count = 1) - Test the condition at the start of each iteration (
while count <= 5) - Update the variable inside the loop (
count = count + 1)
If you forget step 3, you will create an infinite loop!
Count-Controlled vs Condition-Controlled Loops
This is essential exam terminology that you absolutely must know for your GCSE. Exam boards use these terms frequently, so make sure you understand the difference.
| Type | Python Keyword | When to Use | Example Scenario |
|---|---|---|---|
| Count-controlled loop | for |
When you know in advance how many times the loop should run | Print the 7 times table (exactly 12 iterations) |
| Condition-controlled loop | while |
When you do not know how many times it will run — it depends on a condition | Keep asking for a password until the user gets it right |
for) repeats a fixed number of times. A condition-controlled loop (while) repeats until a condition becomes False. In your exam, use these precise terms. If a question says "use a count-controlled loop", it means use a for loop. If it says "use a condition-controlled loop", it means use a while loop.
Here is an easy way to decide which to use:
- "Do this 10 times" → You know the number →
forloop (count-controlled) - "Keep going until the user says stop" → You do not know when →
whileloop (condition-controlled) - "Process every item in this list" → You know the items →
forloop (count-controlled) - "Keep guessing until correct" → Could be 1 guess or 100 →
whileloop (condition-controlled)
break and continue: Controlling Loop Flow
Sometimes you need to exit a loop early or skip certain steps. Python gives you two keywords for this:
break— immediately exits the loop entirelycontinue— skips the rest of the current iteration and moves to the next one
# Using break to exit a loop early
print("--- break example ---")
for i in range(1, 11):
if i == 6:
print("Stopping at 6!")
break
print(i)
# Using continue to skip an iteration
print("\n--- continue example ---")
for i in range(1, 6):
if i == 3:
continue # skip number 3
print(i)
Think of break as an emergency exit — you leave the entire loop immediately. Think of continue as skipping a song on a playlist — you move to the next one without finishing the current one.
Trace Tables: Following a Loop Step by Step
A trace table is a technique for tracking the values of variables as a program runs, line by line. They are essential for your GCSE exam — you will almost certainly be asked to complete one. Trace tables are particularly useful for understanding loops because they show you exactly what happens at each iteration.
Consider this simple while loop:
# Simple doubling program
x = 1
count = 0
while x < 20:
x = x * 2
count = count + 1
print("Iteration", count, "- x =", x)
Here is the trace table for this program:
| Iteration | x (start) |
x < 20? |
x (after x = x * 2) |
count |
|---|---|---|---|---|
| — | 1 | — | — | 0 |
| 1 | 1 | True | 2 | 1 |
| 2 | 2 | True | 4 | 2 |
| 3 | 4 | True | 8 | 3 |
| 4 | 8 | True | 16 | 4 |
| 5 | 16 | True | 32 | 5 |
| — | 32 | False | — | — |
On iteration 5, x becomes 32. When the loop checks the condition again, 32 < 20 is False, so the loop stops. The final value of x is 32 and count is 5.
Worked Example: Finding the Average
Let us work through a complete example step by step. We want to calculate the average of a list of test scores using a for loop and the accumulator pattern.
The problem: A teacher has five test scores: 72, 85, 90, 68, and 95. Calculate the average score.
Step 1: Store the scores in a list and set up an accumulator variable.
Step 2: Loop through each score, adding it to the total.
Step 3: Divide the total by the number of scores.
# Worked Example: Finding the average test score
scores = [72, 85, 90, 68, 95]
total = 0
for score in scores:
total = total + score
print("Added " + str(score) + " - running total: " + str(total))
average = total / len(scores)
print("\nTotal: " + str(total))
print("Number of scores: " + str(len(scores)))
print("Average: " + str(average))
Trace table for this program:
| Iteration | score |
total (before) |
total (after) |
|---|---|---|---|
| — | — | 0 | — |
| 1 | 72 | 0 | 72 |
| 2 | 85 | 72 | 157 |
| 3 | 90 | 157 | 247 |
| 4 | 68 | 247 | 315 |
| 5 | 95 | 315 | 410 |
After the loop, total is 410. Dividing by 5 (the number of scores) gives us an average of 82.0.
Common Mistakes
range(1, 10) produces 1 to 9, not 1 to 10. If you want to include 10, you need range(1, 11). This is the single most frequent bug that students encounter with loops.
while loop, always make sure the condition will eventually become False. For example, if your condition checks while count < 10, you must increase count inside the loop. If you forget, the loop will run forever and your program will freeze. If this happens in the browser, you may need to refresh the page.
Here is a summary of the most common loop mistakes and how to avoid them:
| Mistake | What Goes Wrong | How to Fix It |
|---|---|---|
Off-by-one with range() |
range(1, 10) produces 1–9, not 1–10 |
Use range(1, 11) to include 10 |
Infinite while loop |
Forgetting to update the counter variable | Always change the variable inside the loop |
| Modifying a list while looping | Removing items from a list mid-loop causes skipped items | Loop over a copy of the list, or build a new list |
Using while when for is better |
More code, more chance of bugs | If you know the number of iterations, use for |
| Forgetting the colon | for i in range(5) causes a SyntaxError |
Always end for and while lines with : |
Real-World Applications
Loops are not just a classroom exercise — they are at the heart of almost every piece of technology you use. Here are some real-world examples of loops in action:
Music Players
When you press play on Spotify or Apple Music, a loop iterates through your playlist, playing each song one after another. The "repeat" button is literally a loop — when the playlist ends, the loop starts again from the beginning. Even the progress bar is updated by a loop that runs many times per second.
Search Engines
When you search on Google, a loop runs through billions of indexed web pages to find ones that match your query. These loops are so heavily optimised that they return results in under a second. Without loops, you would have to check each web page manually — which would take several lifetimes.
Video Games
Every video game runs on something called the game loop. This is a while loop that repeats for as long as the game is running. Each time around the loop (called a frame), the game checks for player input, updates the positions of characters and objects, checks for collisions, and draws everything on screen. A game running at 60 frames per second (fps) is executing this loop 60 times every second.
Social Media Feeds
When you scroll through TikTok, Instagram, or YouTube, a loop iterates through a list of posts and renders each one on your screen. As you scroll further, the app fetches more posts and the loop continues. The "infinite scroll" effect is, appropriately enough, powered by a loop.
Scientific Computing
Scientists use loops to run simulations — modelling weather patterns, protein folding, galaxy formation, and more. These simulations can involve loops that run millions or even billions of times. Climate models, for example, divide the atmosphere into a grid and loop through every single cell to calculate temperature, pressure, and wind at each point.
Key Vocabulary
Make sure you understand all of these terms. They come up frequently in exams and in discussions about programming.
| Term | Definition |
|---|---|
| Iteration | The process of repeating a set of instructions. Also refers to a single pass through a loop. |
| For Loop | A count-controlled loop that repeats for each item in a sequence (e.g., a range or list). |
| While Loop | A condition-controlled loop that repeats as long as a given condition is True. |
| Counter | A variable used to keep track of how many times a loop has run. |
| Accumulator | A variable that builds up a value (e.g., a running total) across multiple iterations of a loop. |
range() |
A built-in Python function that generates a sequence of numbers for use in a for loop. |
| Infinite Loop | A loop that never stops because its condition never becomes False. Usually a bug. |
break |
A keyword that immediately exits the current loop. |
continue |
A keyword that skips the rest of the current iteration and moves to the next one. |
| Nested Loop | A loop inside another loop. The inner loop runs completely for each iteration of the outer loop. |
| Count-Controlled Loop | A loop that runs a predetermined number of times. In Python, this is a for loop. |
| Condition-Controlled Loop | A loop that runs until a condition changes. In Python, this is a while loop. |
| Iterate | To go through items one at a time. "Iterating through a list" means visiting each item in turn. |
| Sequence | An ordered collection of items that can be looped through, such as a list, string, or range. |
Your Turn
Use a for loop to print the 5 times table from 5 × 1 up to 5 × 12. Each line should look like 5 x 1 = 5.
CALCULATE the result as 5 multiplied by the number
PRINT the multiplication in the format "5 x number = result"
# Exercise 1: Print the 5 times table
for i in range(____, ____):
result = ____ * ____
print("5 x " + str(____) + " = " + str(____))
You need range(1, 13) to go from 1 to 12 (remember, range stops before the second number). Multiply 5 * i to get each result. Use str() to convert numbers to text for printing.
Write a program that prints all the even numbers from 1 to 20. There are several ways to do this — you could use range() with a step, or use an if statement inside the loop to check each number.
IF the number is even (divisible by 2 with no remainder):
PRINT the number
# Exercise 2: Print all even numbers from 1 to 20
for number in range(1, 21):
# Check if the number is even
# Hint: use the modulo operator %
pass # Replace this with your code
A number is even if dividing it by 2 leaves no remainder. In Python, the modulo operator % gives you the remainder: number % 2 == 0 means the number is even. Alternatively, you could skip the if entirely by using range(2, 21, 2) to step by 2.
Create a program that prints a triangle pattern made of stars (*). For example, if the triangle has 5 rows, the output should look like this:
* ** *** **** *****
Challenge: Can you also make it print an upside-down triangle afterwards?
# Exercise 3: Print a triangle of stars
# Your code here
Think about what each row has in common: row 1 has 1 star, row 2 has 2 stars, row 3 has 3 stars, and so on. You can use string multiplication in Python: "*" * 3 gives "***". So a loop like for row in range(1, 6) with print("*" * row) would do the trick. For the upside-down version, try range(5, 0, -1).
FizzBuzz is a classic programming challenge used in coding interviews around the world. Loop through the numbers 1 to 30. For each number:
- If the number is divisible by both 3 and 5, print
"FizzBuzz" - If the number is divisible by 3 only, print
"Fizz" - If the number is divisible by 5 only, print
"Buzz" - Otherwise, print the number itself
IF number is divisible by 3 AND divisible by 5:
PRINT "FizzBuzz"
ELSE IF number is divisible by 3:
PRINT "Fizz"
ELSE IF number is divisible by 5:
PRINT "Buzz"
ELSE:
PRINT the number
# Exercise 4: FizzBuzz
for number in range(1, 31):
# Check divisibility and print the right output
# Remember: check for BOTH 3 and 5 first!
pass # Replace this with your code
Use the modulo operator % to check divisibility. number % 3 == 0 means divisible by 3, and number % 5 == 0 means divisible by 5. Important: you must check for "both 3 and 5" first (using and), before checking for 3 or 5 individually. If you check for 3 first, numbers like 15 will print "Fizz" instead of "FizzBuzz".
Create a number guessing game using a while loop. The program should have a secret number (set by you), and the player tries to guess it. After each guess, give a hint: "Too high!" or "Too low!". When they guess correctly, tell them how many attempts it took.
Since we cannot use input() in the browser, simulate the guesses using a list (just like Example 7). Set the secret number to 7 and create a list of guesses that eventually reaches 7.
# Exercise 5: Number Guessing Game
secret = 7
guesses = [3, 9, 5, 7] # Simulated guesses
attempt = 0
found = False
# Use a while loop to check each guess
# Give "Too high!" or "Too low!" hints
# When correct, print a congratulations message with the number of attempts
# Your code here
Use while attempt < len(guesses) and not found: as your loop condition. Inside the loop, get the current guess with guesses[attempt], then use if/elif/else to check if it is too high, too low, or correct. Do not forget to increase attempt each time! When the guess is correct, set found = True and print a message.
Chapter Summary
Here is what you have learned in this chapter:
- A loop repeats a block of code multiple times, saving you from writing the same instructions over and over.
- A
forloop (count-controlled) is used when you know how many times you want to repeat — it iterates through a sequence like arange(), list, or string. - A
whileloop (condition-controlled) is used when you do not know how many times to repeat — it keeps going as long as a condition isTrue. - The
range()function generates sequences of numbers and is memory-efficient thanks to lazy evaluation. - The accumulator pattern lets you build up a total or result across iterations of a loop.
- Nested loops place one loop inside another — the inner loop runs completely for each iteration of the outer loop.
breakexits a loop immediately;continueskips to the next iteration.- A trace table helps you track variable values through each iteration of a loop — an essential exam skill.
- The most common mistakes are off-by-one errors with
range()and infinite loops from forgetting to update a counter.
Exam-Style Questions
These questions are written in the style you might see in your GCSE Computer Science exam. Try to answer them on paper before checking the hints.
Explain the difference between a count-controlled loop and a condition-controlled loop. Give an example of when you would use each.
Count-controlled loop (1 mark): A loop that repeats a set number of times. In Python, this is a for loop. (1 mark for example): Printing a times table from 1 to 12 — you know you need exactly 12 iterations.
Condition-controlled loop (1 mark): A loop that repeats until a condition becomes False. In Python, this is a while loop. (1 mark for example): Asking the user for a password until they enter the correct one — you do not know how many attempts it will take.
Complete the trace table for the following code:
x = 10
total = 0
while x > 0:
total = total + x
x = x - 3
print(total)
| Iteration | x (start) |
x > 0? |
total |
x (end) |
|---|---|---|---|---|
| — | 10 | — | 0 | — |
| 1 | ? | ? | ? | ? |
| 2 | ? | ? | ? | ? |
| 3 | ? | ? | ? | ? |
| 4 | ? | ? | ? | ? |
What value is printed at the end?
Iteration 1: x=10, 10>0 is True, total=0+10=10, x=10-3=7
Iteration 2: x=7, 7>0 is True, total=10+7=17, x=7-3=4
Iteration 3: x=4, 4>0 is True, total=17+4=21, x=4-3=1
Iteration 4: x=1, 1>0 is True, total=21+1=22, x=1-3=-2
Now x=-2, and -2>0 is False, so the loop ends. The program prints 22.
(1 mark for each correctly completed row, up to 3 marks.)
A student writes the following code, expecting it to print the numbers 1 to 10:
for i in range(1, 10):
print(i)
Explain why this does not produce the expected output and how to fix it.
(1 mark): The range() function stops before the second number, so range(1, 10) only produces the numbers 1 to 9. The number 10 is not included.
(1 mark): To fix this, change the code to range(1, 11) so that the range includes 10.
Think About It
- When would you choose a
forloop over awhileloop? Can you think of a situation where only awhileloop would work well? - Why does
range(1, 5)only produce four numbers (1, 2, 3, 4) and not five? Why do you think Python was designed this way? - What would happen if you put a loop inside another loop? Where might that be useful?
- Can you think of three everyday activities that involve loops? What would the "condition" be for each one to stop?
- In a game loop running at 60fps, roughly how many loop iterations happen in a 10-minute gaming session?
Interactive Activities
- Trace Table Challenge — Step through loop execution and track how variables change on each iteration
- Trace Table Challenge 2 — More advanced program tracing with nested loops and output tracking
Extra Practice & Resources
Test your loop skills with these interactive challenges and external resources:
- Program Builder — Drag and drop code blocks into the right order to build working programs
- Python Code Fixer — Find and fix bugs in Python programs that use loops
- GCSE Topic 6: Control Flow — For loops, while loops, and nested structures with code editors
- BBC Bitesize Edexcel CS — Comprehensive revision materials for Edexcel GCSE Computer Science
- W3Schools: Python For Loops — Interactive tutorials and examples for for loops
- W3Schools: Python While Loops — Interactive tutorials and examples for while loops
What's Next?
In Chapter 6: Functions, you will learn how to package loops and logic into reusable blocks of code. What if you could write your times table printer once and then call it for any number — not just 5? Functions make that possible.