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.

01

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.
0 or 1 weak itemsContinue with this module.
2 weak itemsRevisit conditionals in Module 4.
3 or more weak itemsRevisit the calculator in Module 1.
02

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.

for i in range(1, 101): total += irange(1, 101) gives 1 to 100while condition: ... (repeat)

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 skill works when: you initialise an accumulator, loop over the right range, and update it each pass.
The skill breaks down when: the range bound is off by one, or a while loop never updates its condition.
The concept. A loop takes each item in turn and updates a running result, repeating until the sequence is exhausted.
03

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.

LoopUse whenWatch for
for over rangeyou know the countoff-by-one bound
for over a listyou have datamodifying while iterating
whilecount depends on resultinfinite 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.

04

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
  1. ProblemSum the integers 1 through 100.
  2. Given / findThe numbers 1 to 100. Find their total.
  3. ModelAccumulate: start at 0, add each i.
  4. Coderange(1, 101) reaches 100 because the upper bound is excluded.
  5. Solvetotal = 5050.
  6. CheckThe formula n(n+1)/2 = 100 times 101 over 2 = 5050, matching.
  7. ConclusionA loop plus an accumulator replaces a hundred additions with four lines.
Result. total = 5050.
05

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
  1. ProblemFind 5 factorial with a loop.
  2. Given / findThe numbers 1 to 5. Find their product.
  3. ModelAccumulate a product: start at 1, multiply by each k.
  4. CodeFor a product the accumulator starts at 1, not 0.
  5. Solveresult = 1 times 2 times 3 times 4 times 5 = 120.
  6. Check5 factorial is 120, matching.
  7. ConclusionThe same pattern sums or multiplies, depending on the starting value and operation.
Result. result = 120.
06

Misconceptions and diagnostics

MistakeSymptomDiagnostic questionCorrection
Off-by-one rangeLoop stops one short"Is the upper bound excluded?"range(1, 101) reaches 100.
Accumulator not initialisedA name error or wrong total"Did I set total before the loop?"Start at 0 for sums, 1 for products.
Infinite while loopThe program never stops"Does the tested variable change?"Update the condition variable each pass.
Wrong start for a productProduct is always 0"Did I start at 1?"A product accumulator starts at 1.
07

Practice ladder

Level 1 · Direct skill

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.

Level 2 · Mixed concept

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.

Level 3 · Independent problem

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

Transfer task | Real engineering

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.

08

Working with AI, and proving it yourself

Use AI as a tutor, not a black box

"Explain why range(1, 101) is needed to reach 100."
"Give me a loop; I will predict the final total, then run it."
"Write my loop." Draft the accumulator yourself.
"Why is my loop infinite?" Check that the condition variable changes.

Portfolio task

Write a loop that processes a list of engineering values into a single summary (sum, average, or maximum) and prints it.

Must include: an initialised accumulator, a correct loop range or list, and a labeled result.
09

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.

TodayFinish this quiz and Levels 1 and 2 of the ladder.
+1 dayRe-derive the sum and factorial from memory.
+3 daysLoop over a real dataset into one summary.
+7 daysMove on to functions in Module 6.
+30 daysSee numerical methods as loops with accumulators.
10

Textbook mapping

This module follows Hans Fangohr, Introduction to Python for Computational Science and Engineering. Use these references to read further.

Topic in this moduleWhere to read more
The for loopFangohr, Section 6.3, For loop
The while loopFangohr, Section 6.4, While loop
Control flow and iterationFangohr, 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.