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:

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.

Predict First! The code uses range(1, 6). How many numbers will it print? Will it include 6? Careful — this is a common exam trap!
1
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.
Python Code
# Counting from 1 to 5 using a for loop
for number in range(1, 6):
    print(number)
(click "Run Code" to see output)
Try This: Change 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.

Python Code
# Looping through a list of fruits
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print("I like " + fruit)
(click "Run Code" to see output)
Try This: Add more fruits to the list, such as "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!"

Predict First! Trace through this code carefully. The variable 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?
5
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.
Python Code
# Countdown using a while loop
countdown = 5

while countdown > 0:
    print(countdown)
    countdown = countdown - 1

print("Blast off!")
(click "Run Code" to see output)
Try This: Change the starting number to 10 for a longer countdown. What would happen if you removed the line 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.

Python Code
# 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)
(click "Run Code" to see output)
Try This: Change both 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.

Python Code
# Looping through each character in a word
word = "Python"

for letter in word:
    print(letter, "- ASCII code:", ord(letter))
(click "Run Code" to see output)
Try This: Change the word to your own name. Can you modify the program to count how many vowels are in the word? (Hint: check if 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.

Python Code
# 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)
(click "Run Code" to see output)
Try This: Gauss found the answer was 5050 — does your program agree? Now try calculating the sum of 1 to 1000. Can you modify it to only add up the even numbers?

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.)

Python Code
# 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.")
(click "Run Code" to see output)
Try This: Change the guesses list so that the correct password is entered on the first attempt. What happens if none of the guesses are correct? Try changing 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:

Python Code
# 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)
(click "Run Code" to see output)

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).

Did You Know? The 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:

Python Code
# Structure of a while loop
count = 1

while count <= 5:
    print("Count is:", count)
    count = count + 1

print("Loop finished!")
(click "Run Code" to see output)

Notice the three essential parts of a while loop:

  1. Initialise the variable before the loop (count = 1)
  2. Test the condition at the start of each iteration (while count <= 5)
  3. 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
Key Concept — Exam Terminology: A count-controlled loop (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:

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:

Python Code
# 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)
(click "Run Code" to see output)

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:

Python Code
# Simple doubling program
x = 1
count = 0

while x < 20:
    x = x * 2
    count = count + 1
    print("Iteration", count, "- x =", x)
(click "Run Code" to see output)

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.

Exam Tip: When filling in a trace table, always write down the initial values before the loop starts. Then work through each iteration carefully, updating one variable at a time. Pay close attention to the order of operations — the condition is checked at the start of each iteration, not the end.

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.

Python Code
# 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))
(click "Run Code" to see output)

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

Watch out — Off-by-One Errors! The most common loop mistake is the off-by-one error. Remember that 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.
Watch out — Infinite Loops! If you write a 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 :
Did You Know? The concept of a loop was one of Ada Lovelace's key insights when she wrote the first algorithm in 1843 — over 100 years before electronic computers existed! She realised that Charles Babbage's Analytical Engine could repeat a set of instructions, making it fundamentally different from a simple calculator. This insight is one of the reasons she is often called the world's first computer programmer.

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.

Did You Know? The fastest supercomputers in the world can execute loops at a staggering rate. The Frontier supercomputer at Oak Ridge National Laboratory can perform over one quintillion (1,000,000,000,000,000,000) calculations per second. That means a loop body could theoretically execute billions of times in the blink of an eye.

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

Exercise 1: The 5 Times Table
Guided

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.

Pseudocode:
FOR each number from 1 to 12:
  CALCULATE the result as 5 multiplied by the number
  PRINT the multiplication in the format "5 x number = result"
Your Code
# Exercise 1: Print the 5 times table
for i in range(____, ____):
    result = ____ * ____
    print("5 x " + str(____) + " = " + str(____))
(click "Run Code" to see output)
Need a hint?

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.

Exercise 2: Even Numbers
Partially Guided

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.

Pseudocode:
FOR each number from 1 to 20:
  IF the number is even (divisible by 2 with no remainder):
    PRINT the number
Your Code
# 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
(click "Run Code" to see output)
Need a hint?

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.

Exercise 3: Star Triangle
Open-Ended

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?

Your Code
# Exercise 3: Print a triangle of stars
# Your code here
(click "Run Code" to see output)
Need a hint?

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).

Exercise 4: FizzBuzz
Partially Guided

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
Pseudocode:
FOR each number from 1 to 30:
  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
Your Code
# 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
(click "Run Code" to see output)
Need a hint?

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".

Exercise 5: Number Guessing Game
Open-Ended

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.

Your Code
# 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
(click "Run Code" to see output)
Need a hint?

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:

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.

Question 1 (4 marks)
Written Answer

Explain the difference between a count-controlled loop and a condition-controlled loop. Give an example of when you would use each.

Guidance

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.

Question 2 (3 marks)
Trace Table

Complete the trace table for the following code:

Python Code
x = 10
total = 0

while x > 0:
    total = total + x
    x = x - 3

print(total)
(click "Run Code" to see output)
Iteration x (start) x > 0? total x (end)
10 0
1 ? ? ? ?
2 ? ? ? ?
3 ? ? ? ?
4 ? ? ? ?

What value is printed at the end?

Guidance

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.)

Question 3 (2 marks)
Short Answer

A student writes the following code, expecting it to print the numbers 1 to 10:

Python Code
for i in range(1, 10):
    print(i)
(click "Run Code" to see output)

Explain why this does not produce the expected output and how to fix it.

Guidance

(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

Interactive Activities

Extra Practice & Resources

Test your loop skills with these interactive challenges and external resources:

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.