Count-Controlled Iteration: FOR Loops
Repeating a block of code a known number of times. This lesson covers Python's range() function, step values, iteration over collections, nested loops, and the common patterns that appear in every exam.
Imagine having to print "Hello" 1000 times. Writing 1000 print statements would take an hour and produce a 1000-line file. A FOR loop does it in two lines. But loops are not just about saving keystrokes - they are the mechanism behind searching a list, processing every row in a spreadsheet, drawing every pixel on a screen, and simulating every second of a physics model. Once you can loop, you can automate anything that has a pattern.
A FOR loop iterates over a sequence. range() generates that sequence. The three-argument form is range(start, stop, step) - stop is never included.
# range(stop) - from 0 up to (not including) stop for i in range(5): print(i) # 0 1 2 3 4 # range(start, stop) - from start up to stop for i in range(1, 6): print(i) # 1 2 3 4 5 # range(start, stop, step) - step of 2 for i in range(0, 10, 2): print(i) # 0 2 4 6 8 # Counting down with negative step for i in range(5, 0, -1): print(i) # 5 4 3 2 1
// C# for loop: for(init; condition; update) for (int i = 0; i < 5; i++) { Console.WriteLine(i); // 0 1 2 3 4 } // From 1 to 5 inclusive for (int i = 1; i <= 5; i++) Console.WriteLine(i); // 1 2 3 4 5 // Step of 2 for (int i = 0; i < 10; i += 2) Console.WriteLine(i); // 0 2 4 6 8 // Counting down for (int i = 5; i > 0; i--) Console.WriteLine(i); // 5 4 3 2 1
range(1, 6) generates 1, 2, 3, 4, 5 - NOT 6. The stop value is excluded. This is consistent with Python's slicing (s[1:4] excludes index 4). In C#, i <= 5 includes 5 because you are writing the condition explicitly. Always count the values to check your range boundaries.
Common loop patterns:
# Accumulator pattern - sum numbers 1 to 10 total = 0 # initialise BEFORE the loop for i in range(1, 11): total = total + i # or: total += i print(total) # 55 # Iterate over a list (see Lesson 7 for full list coverage) names = ["Alice", "Bob", "Carol"] for name in names: print("Hello,", name) # Multiplication table row for 7 for i in range(1, 13): print(f"7 x {i} = {7 * i}")
In exam trace questions, always track: (1) the loop variable value at the start of each iteration, (2) any accumulator variable after each iteration, and (3) the total number of iterations. For range(a, b, s), the number of iterations is ceil((b-a)/s). Common error: forgetting to initialise accumulators to 0 before the loop (putting them inside means they reset each iteration).
A nested loop has an inner loop that runs completely for each iteration of the outer loop. If the outer loop runs N times and the inner loop runs M times, the inner body executes N * M times in total.
# Nested loop: multiplication table (3 rows x 3 cols = 9 cells) for row in range(1, 4): # outer: 3 iterations for col in range(1, 4): # inner: 3 iterations per outer print(row * col, end=" ") print() # newline after each row # Output: # 1 2 3 # 2 4 6 # 3 6 9
// C# nested loop: multiplication table for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { Console.Write(row * col + " "); } Console.WriteLine(); }
| Iteration | i (loop var) | total (accumulator: total += i) |
|---|
Three Quick Challenges
What does this accumulator loop print? Trace through each iteration.
total = 0 for i in range(1, 5): total += i print(total)
int total = 0; for (int i = 1; i < 5; i++) total += i; Console.WriteLine(total);
Complete the loop to count from 0 to 4:
This loop crashes with a NameError. What is missing?
for i in range(1, 6): total += i print(total)
Test yourself
1. How many times does the body of for i in range(3, 8) execute?
2. What are the values produced by range(0, 10, 3)?
3. A student initialises total = 0 inside a FOR loop. What is the bug?
4. If an outer loop runs 4 times and an inner loop runs 3 times, how many times does the inner body execute?
5. What is the output of: for i in range(5, 0, -2): print(i)?
Write a program that uses a FOR loop to find the largest number in a list of 10 integers entered by the user. You cannot use Python's max() function or C#'s LINQ Max(). You must use a loop and a variable that tracks the current maximum. What should the initial value of the maximum variable be, and why?
numbers = []for i in range(10): numbers.append(int(input("Number " + str(i+1) + ": ")))maximum = numbers[0] # initialise to first elementfor num in numbers: if num > maximum: maximum = numprint("Largest:", maximum)Initial value choice: Initialise to numbers[0] (the first element). Do NOT initialise to 0 or -1 - if all numbers are negative, 0 or -1 would incorrectly be "larger" than all of them. Using the first element guarantees the answer is always from the actual dataset. Alternatively, use Python's float('-inf') (negative infinity) which is guaranteed to be smaller than any real number.
Practice what you have learned
Three levelled worksheets. Download, print and complete offline.