A4 · Lesson 8 · Loops
Let the computer do it a million times
Most of what makes code worth writing is repetition: step a simulation through ten thousand time steps, add up a series until it settles, try every resistor in a range, refine an estimate until it stops changing. Python has two loops. for repeats a known number of times; while repeats until a condition changes. Between them they cover every kind of repetition a numerical method needs.
Predict
What does this print?
total = 0
for k in range(1, 5):
total += k
print(total)
range(1, 5)gives 1, 2, 3 and 4: it starts at the first number and stops before the second. So the loop adds . The stop-before rule is the most common off-by-one trap in Python.
Name it
for loops
for k in range(n): # k = 0, 1, ..., n-1
...
for k in range(a, b): # k = a, ..., b-1
for k in range(a, b, s): # in steps of s
The accumulator pattern builds a result across the loop:
total = 0
for k in range(n):
total += term(k)
and so does tracking the best so far:
best = None
for x in candidates:
if best is None or score(x) > score(best):
best = x
while loops
while condition: repeats as long as the condition is true. Use it when you don't know in advance how many steps you'll need:
n = 0
while 2**n < M: # smallest n with 2**n >= M
n += 1
Make sure the loop ends. Something in the body has to move the condition toward false. A safety limit is cheap insurance:
for _ in range(10000):
...
if converged:
break
break leaves a loop early; continue skips to the next pass.
Iterating to a fixed point
Many numerical methods repeat a formula until the answer stops changing. To find , start anywhere and repeat :
x = a
while abs(x * x - a) > 1e-12 * a:
x = 0.5 * (x + a / x)
Each pass roughly doubles the number of correct digits. This is Newton's method (A6 and lesson 37), and the pattern of "update, test, repeat" is the same for every iterative solver.
Worked example
Add up until the next term is below .
Show the solution
- Loop while the term is big enough. Add the term, then halve it.
total, term = 0.0, 1.0
while term >= 1e-9:
total += term
term /= 2
print(total) # 1.9999999981373549
- Count the terms. The loop stops after 30 terms.
- Check against the formula. The sum is within of the exact 2 from A2's geometric series formula, which is a good check that the loop is right.
Answer 30 terms add up to 1.9999999981, within of the exact 2.
Worked example
A capacitor charges as . Stepping in units of , after how many steps is it above 0.99?
Show the solution
- Step until the voltage passes 0.99. Count steps of in a
whileloop.
import math
k = 0
while 1 - math.exp(-k * 0.1) <= 0.99:
k += 1
print(k, k * 0.1) # 47 4.7
- Read the result. 47 steps, .
- Check against the exact crossing. It is at and the loop reports the first step past it.
Answer after 47 steps, at .
Check
A ladder has n = 15 resistors in series: the first is R0 = 100 Ω and each one after is d = 10 Ω bigger. Set total to their sum, using a for loop.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Using a while loop, set n to the smallest whole number with M = 1000.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Find for a = 10 by repeating from until . Set x to the result and steps to how many updates it took.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A capacitor charges as after k steps of . Set k to the first step at which it exceeds f = 0.95.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
An RC low-pass driven by a 1 V step obeys when stepped forward by Euler's method, with . Starting from , run n = 50 steps with r = 0.1 in a for loop. Set v to the final value and err to how far it is from the exact .
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
How many times does the body of for k in range(2, 11, 3): run?
Explain why
When would you use while instead of for?
for is for repeating a known number of times or going through a known collection, like stepping through 1000 samples. while is for repeating until something becomes true when you can't say in advance how many passes that takes, like refining an estimate until it stops changing or counting until a total crosses a threshold. With while you have to make sure the condition eventually changes, or the loop never ends.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.