Programming and Computation · Module 5 of 10
Loops and Iteration
Computers earn their keep by repeating work without tiring. This module covers the for loop over a range or a list, the accumulator pattern for running totals, and the while loop for condition-controlled repetition.
Readiness check
This module is about repetition. Tick only what you can do closed-notes.
- Recall a running total from mental arithmetic.
- Recall counting from a start to an end.
- Use variables, conditionals, and printing from earlier modules.
- Recall a factorial or a sum of a series.
- Recall that indentation defines a block.
The core idea
A for loop repeats a block once for each item in a sequence, such as the numbers from range() or the entries of a list. A running result is built with the accumulator pattern, total = total + x. A while loop instead repeats as long as a condition stays true.
Repetition is where code beats hand calculation. A for loop walks through a sequence, running its indented block once per item. The most common sequence is range(a, b), which yields the integers from a up to but not including b, so range(1, 101) produces 1 through 100. To combine the items into one answer you use the accumulator pattern: start a variable at zero (or one, for products), then update it each pass, total = total + i, often written total += i. Summing 1 to 100 this way gives 5050 without typing a hundred additions. The other loop is the while loop, which repeats as long as a condition is true and stops when it becomes false, useful when you do not know the count in advance, such as iterating until an error is small enough. Two hazards come with loops: the off-by-one error, where range excludes its upper bound so you must write 101 to reach 100, and the infinite loop, where a while condition never becomes false because you forgot to change the variable it tests. Loops turn a formula evaluated once into a computation repeated over a whole dataset or series, the heart of numerical work.
The skills, taught in order
Five skills make repetition reliable.
5.1 for loops and range
for i in range(a, b): runs the block for each integer from a up to but not including b. Use range(n) for 0 to n minus 1, or range(a, b) for a chosen span.
5.2 The accumulator pattern
Start a result variable before the loop, then update it inside: total = 0 then total += i. For products start at 1 and multiply. This turns a sequence into a single summarised value.
5.3 while loops
while condition: repeats as long as the condition is true. Use it when the number of repetitions depends on the result, such as looping until a residual is below a tolerance.
| Loop | Use when | Watch for |
|---|---|---|
for over range | you know the count | off-by-one bound |
for over a list | you have data | modifying while iterating |
while | count depends on result | infinite loop |
Pick the loop that matches how the repetition is controlled.
5.4 Looping over data
A for loop can walk a list directly: for load in loads: gives each value in turn, ideal for processing measurements or design cases (Module 7).
5.5 Avoiding infinite and off-by-one loops
In a while loop, make sure the tested variable actually changes each pass, or it never ends. With range, remember the upper bound is excluded, so add one to reach it.
Engineering connection: summing a series, integrating numerically, or iterating a solver until it converges are all loops, which is why every numerical-methods technique later is built from them.
Worked example 1: sum of 1 to 100
Add the integers from 1 to 100 using a for loop and an accumulator.
total = 0
for i in range(1, 101):
total = total + i
print(total)
Output:
5050
- ProblemSum the integers 1 through 100.
- Given / findThe numbers 1 to 100. Find their total.
- ModelAccumulate: start at 0, add each
i. - Code
range(1, 101)reaches 100 because the upper bound is excluded. - Solvetotal = 5050.
- CheckThe formula n(n+1)/2 = 100 times 101 over 2 = 5050, matching.
- ConclusionA loop plus an accumulator replaces a hundred additions with four lines.
Worked example 2: a factorial
Compute 5 factorial (5 times 4 times 3 times 2 times 1) with a loop.
result = 1
for k in range(1, 6):
result = result * k
print(result)
Output:
120
- ProblemFind 5 factorial with a loop.
- Given / findThe numbers 1 to 5. Find their product.
- ModelAccumulate a product: start at 1, multiply by each
k. - CodeFor a product the accumulator starts at 1, not 0.
- Solveresult = 1 times 2 times 3 times 4 times 5 = 120.
- Check5 factorial is 120, matching.
- ConclusionThe same pattern sums or multiplies, depending on the starting value and operation.
Misconceptions and diagnostics
| Mistake | Symptom | Diagnostic question | Correction |
|---|---|---|---|
| Off-by-one range | Loop stops one short | "Is the upper bound excluded?" | range(1, 101) reaches 100. |
| Accumulator not initialised | A name error or wrong total | "Did I set total before the loop?" | Start at 0 for sums, 1 for products. |
| Infinite while loop | The program never stops | "Does the tested variable change?" | Update the condition variable each pass. |
| Wrong start for a product | Product is always 0 | "Did I start at 1?" | A product accumulator starts at 1. |
Practice ladder
Use a loop to add the squares of 1 to 5.
Show answer
total = 0; for i in range(1, 6): total += i ** 2 gives 1+4+9+16+25 = 55.
Write a while loop that counts down from 5 to 1 and prints each value.
Show answer
k = 5; while k >= 1: print(k); k = k - 1. The k = k - 1 is what ends the loop.
Given a list loads = [10, 12, 14, 16, 18], compute the average with a loop.
Show answer
Sum with a loop to get 70, divide by the count 5, giving 14.0. Or use sum(loads) / len(loads) (Module 7).
Loop over five positions along a beam and print the deflection at each, using a deflection formula from a past course.
What good work looks like
A for loop over the positions that computes and prints a formatted deflection at each. A good answer uses the loop variable in the formula and labels each output.
Working with AI, and proving it yourself
Use AI as a tutor, not a black box
Portfolio task
Write a loop that processes a list of engineering values into a single summary (sum, average, or maximum) and prints it.
Retrieval and spaced review
Closed notes. Answer out loud, then reveal.
1. What does range(1, 101) produce?
The integers 1 through 100 (upper bound excluded).
2. What is the accumulator pattern?
Initialise a result, then update it each pass.
3. When do you use a while loop?
When the number of repetitions depends on the result.
4. What starts a product accumulator?
1, not 0.
5. What causes an infinite loop?
A while condition whose variable never changes.
Textbook mapping
This module follows Hans Fangohr, Introduction to Python for Computational Science and Engineering. Use these references to read further.
| Topic in this module | Where to read more |
|---|---|
| The for loop | Fangohr, Section 6.3, For loop |
| The while loop | Fangohr, Section 6.4, While loop |
| Control flow and iteration | Fangohr, Chapter 6, Control Flow |
Chapter numbers refer to Fangohr's Introduction to Python for Computational Science and Engineering. Any recent version is equivalent for study.