---
title: Repeating with for and while
heading: Let the computer do it a million times
eyebrow: A4 · Lesson 8 · Loops
xp: 40
---

::: hook
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)
```

- [ ] 15
- [x] 10
- [ ] 4
- [ ] 5

::: reveal
10. `range(1, 5)` gives 1, 2, 3 and 4: it starts at the first number and stops *before* the second. So the loop adds $1 + 2 + 3 + 4 = 10$. The stop-before rule is the most common off-by-one trap in Python.
:::
:::

::: nameit
## 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 $\sqrt{a}$, start anywhere and repeat $x \leftarrow \frac{1}{2}(x + a/x)$:

```
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.
:::

::: example
## Add up $1 + \frac{1}{2} + \frac{1}{4} + \cdots$ until the next term is below $10^{-9}$.

::: solution
1. **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
```

2. **Count the terms.** The loop stops after 30 terms.
3. **Check against the formula.** The sum is within $2 \times 10^{-9}$ 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 $2 \times 10^{-9}$ of the exact 2.
:::
:::

::: example
## A capacitor charges as $v = 1 - e^{-t/\tau}$. Stepping $t$ in units of $0.1\tau$, after how many steps is it above 0.99?

::: solution
1. **Step until the voltage passes 0.99.** Count steps of $0.1\tau$ in a `while` loop.

```
import math
k = 0
while 1 - math.exp(-k * 0.1) <= 0.99:
    k += 1
print(k, k * 0.1)     # 47 4.7
```

2. **Read the result.** 47 steps, $4.7\tau$.
3. **Check against the exact crossing.** It is at
   $$\begin{aligned} t &= \tau \ln 100 \\ &= 4.605\,\tau \end{aligned}$$
   and the loop reports the first step past it.

**Answer:** after 47 steps, at $4.7\tau$.
:::
:::

::: check
kind: python
given: R0 = 100 | 220; d = 10 | 47; n = 5..20 int

## A ladder has `n` = {n} resistors in series: the first is `R0` = {R0} Ω and each one after is `d` = {d} Ω bigger. Set `total` to their sum, using a `for` loop.

```python starter
total = 0
for k in range(n):
    total = R0 + k * d
print(total)
```

```python solution
total = 0
for k in range(n):
    total += R0 + k * d
print(total)
```

```python tests
want = sum(R0 + k * d for k in range(n))
assert abs(total - want) < 1e-9, f"total should be {want}. Use += to add each resistor to the running total; = replaces it."
```

::: right
Right. `+=` accumulates; `=` would just keep the last one.
:::
:::

::: check
kind: python
given: M = 300 | 1000 | 5000 | 65537 | 1000000

## Using a `while` loop, set `n` to the smallest whole number with $2^n \ge$ `M` = {M}.

```python starter
n = 0
print(n)
```

```python solution
n = 0
while 2**n < M:
    n += 1
print(n)
```

```python tests
import math
assert 2**n >= M, "2**n should reach M."
assert n == 0 or 2**(n - 1) < M, "n should be the smallest that works: 2**(n-1) is still below M."
```

::: right
Right. The loop stops the first time $2^n$ reaches M, which makes it the smallest answer. Writing `<=` instead of `<` would go one too far whenever M is a power of 2.
:::
:::

::: check
kind: python
given: a = 2 | 10 | 50 | 1000

## Find $\sqrt{a}$ for `a` = {a} by repeating $x \leftarrow \frac{1}{2}(x + a/x)$ from $x = a$ until $|x^2 - a| \le 10^{-12}a$. Set `x` to the result and `steps` to how many updates it took.

```python starter
x = a
steps = 0
print(x, steps)
```

```python solution
x = a
steps = 0
while abs(x * x - a) > 1e-12 * a:
    x = 0.5 * (x + a / x)
    steps += 1
print(x, steps)
```

```python tests
import math
assert abs(x * x - a) <= 1e-12 * a, "x isn't converged yet: loop until |x² − a| ≤ 1e-12·a."
assert steps > 0 and steps < 30, "Count each update in steps."
```

::: right
Right. Ten or so updates gives sixteen correct digits: this method converges fast once it's close.
:::
:::

::: check
kind: python
given: f = 0.9 | 0.95 | 0.99 | 0.999

## A capacitor charges as $1 - e^{-k \cdot 0.1}$ after `k` steps of $0.1\tau$. Set `k` to the first step at which it exceeds `f` = {f}.

```python starter
import math
k = 0
print(k)
```

```python solution
import math
k = 0
while 1 - math.exp(-k * 0.1) <= f:
    k += 1
print(k)
```

```python tests
import math
assert 1 - math.exp(-k * 0.1) > f, f"At step {k} it hasn't passed {f} yet."
assert k == 0 or 1 - math.exp(-(k - 1) * 0.1) <= f, "That's past the first step that works."
```

::: right
Right. The answer sits just above $10\ln\big(1/(1 - f)\big)$, the exact crossing in steps.
:::
:::

::: check
kind: python
given: n = 10 | 50 | 100; r = 0.1 | 0.05 | 0.02

## An RC low-pass driven by a 1 V step obeys $v_{k+1} = v_k + r\,(1 - v_k)$ when stepped forward by Euler's method, with $r = \Delta t/\tau$. Starting from $v = 0$, run `n` = {n} steps with `r` = {r} in a `for` loop. Set `v` to the final value and `err` to how far it is from the exact $1 - e^{-nr}$.

```python starter
import math
v = 0.0
for k in range(n):
    v = r * (1 - v)
err = 0
print(v, err)
```

```python solution
import math
v = 0.0
for k in range(n):
    v = v + r * (1 - v)
err = abs(v - (1 - math.exp(-n * r)))
print(v, err)
```

```python tests
import math
w = 0.0
for _ in range(n):
    w += r * (1 - w)
assert abs(v - w) < 1e-12, f"After {n} steps v should be {w:.6f}: each step adds r*(1 - v) to v."
assert abs(v - (1 - (1 - r)**n)) < 1e-12, "Check the update: v = v + r*(1 - v)."
assert abs(err - abs(w - (1 - math.exp(-n * r)))) < 1e-12, "err is abs(v - (1 - exp(-n*r)))."
```

::: right
Right. Each step multiplies the gap $1 - v$ by $1 - r$, so after {n} steps it's $(1 - r)^n$ against the exact $e^{-nr}$. The error shrinks as $r$ does, which is why small time steps matter.
:::
:::

::: check
kind: choice

## How many times does the body of `for k in range(2, 11, 3):` run?

- [x] 3
- [ ] 4
- [ ] 9
- [ ] 10

::: right
Right. `range(2, 11, 3)` counts 2, 5, 8 and stops before 11, so the body runs three times.
:::

::: misses
- [2] The next value after 8 would be 11, and `range` stops before its end value.
- [3] That counts from 2 to 10 in steps of 1. The third argument is the step, 3.
- [4] `range` never includes its end value, and it steps by 3 here.
:::
:::

::: explain
## When would you use `while` instead of `for`?

::: model
`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

::: check
kind: python
given: n = 5..15 int

## Set `f` to $n!$ for `n` = {n}, with a `for` loop.

```python starter
f = 0
print(f)
```

```python solution
f = 1
for k in range(2, n + 1):
    f *= k
print(f)
```

```python tests
import math
assert f == math.factorial(n), "f should be n! = 1 × 2 × ... × n. Start the product at 1."
```
:::

::: check
kind: python
given: lo = 1 | 10 | 50; hi = 100 | 200; m = 3 | 7

## Set `count` to how many whole numbers from `lo` = {lo} to `hi` = {hi} inclusive are multiples of `m` = {m}.

```python starter
count = 0
print(count)
```

```python solution
count = 0
for k in range(lo, hi + 1):
    if k % m == 0:
        count += 1
print(count)
```

```python tests
assert count == sum(1 for k in range(lo, hi + 1) if k % m == 0), "Count the k with k % m == 0, including hi."
```
:::

::: check
kind: python
given: r = 0.02 | 0.05; target = 0.5 | 0.25

## A battery keeps $1 - r$ of its charge each month (`r` = {r}). Set `months` to the first whole month when it's at or below `target` = {target} of full.

```python starter
months = 0
print(months)
```

```python solution
months = 0
level = 1.0
while level > target:
    level *= 1 - r
    months += 1
print(months)
```

```python tests
assert (1 - r)**months <= target, "At that month it should be at or below the target."
assert months == 0 or (1 - r)**(months - 1) > target, "That's past the first month that works."
```
:::
:::
