---
title: Modules and the standard library
heading: Most of the code you need is already written
eyebrow: A4 · Lesson 19 · Modules and the standard library
xp: 40
---

::: hook
Python comes with a large **standard library**: modules for math with real and complex numbers, random numbers, statistics, dates, files and much more, all tested by millions of users. Before writing a function for a square root, a phase angle or a standard deviation, it's worth knowing it's one import away. And when your own code grows, splitting it into modules is how you keep it organized.
:::

::: predict
## After `import cmath`, what does `cmath.phase(1j)` return?

- [ ] 90
- [x] 1.5707963267948966
- [ ] `1j`
- [ ] An error, because phases need two numbers

::: reveal
$\pi/2$, about 1.5708. `cmath.phase` gives the angle of a complex number in radians, like `math.atan2` does for a point. `math.degrees` converts it to 90°.
:::
:::

::: nameit
## Importing

```
import math                 # use as math.sqrt(2)
from math import pi, sqrt   # use as sqrt(2)
import statistics as st     # use as st.mean(x)
```

Prefer `import math` and the `math.` prefix in anything longer than a few lines: it says where each name comes from.

## Modules worth knowing

| Module | For | Examples |
|---|---|---|
| `math` | real math | `sqrt`, `exp`, `log`, `log10`, `sin`, `atan2`, `hypot`, `degrees`, `radians`, `isclose`, `pi`, `inf` |
| `cmath` | complex math | `sqrt(-4)` → `2j`, `exp`, `phase`, `polar`, `rect` |
| `random` | random numbers | `seed`, `random`, `uniform`, `gauss`, `choice`, `shuffle` |
| `statistics` | summaries | `mean`, `median`, `stdev`, `pstdev` |
| `itertools` | combinations | `product`, `combinations` |

## Complex numbers

Python writes $j$ after a number: `3 + 4j`, `1j`. `abs(z)` is the magnitude and `cmath.phase(z)` the angle in radians:

```
import cmath, math
w = 2 * math.pi * 1000
Z = 1000 + 1 / (1j * w * 100e-9)          # 1 kΩ in series with 100 nF at 1 kHz
print(abs(Z), math.degrees(cmath.phase(Z)))    # 1879.6 -57.86
```

## Random numbers you can repeat

`random.seed(n)` starts the generator at a fixed point, so the "random" numbers come out the same each run, which is essential for debugging and testing. Without a seed, each run differs.

```
import random
random.seed(1)
draws = [random.uniform(0.95, 1.05) for _ in range(5)]
```

## Your own modules

Any `.py` file is a module: put `def` statements in `filters.py` and `import filters` elsewhere. In these browser labs everything is one file, but on your own machine, splitting reusable functions into modules (and their tests into test files) is how projects stay manageable.
:::

::: example
## Find the impedance of 1 kΩ in series with 100 nF at 1 kHz, in polar form.

::: solution
1. **Build the impedance as a complex number.** The capacitor adds $1/(j\omega C)$ to the 1 kΩ.

```
import cmath, math
w = 2 * math.pi * 1000
Z = 1000 + 1 / (1j * w * 100e-9)
r, phi = cmath.polar(Z)
print(f"{r:.4g} Ω at {math.degrees(phi):.4g}°")     # 1880 Ω at -57.86°
```

2. **Convert to polar.** `cmath.polar` returns the magnitude and angle together.
3. **Check by hand.** A3's hand calculation gives the same:
   $$\begin{aligned} |Z| &= \sqrt{1000^2 + 1592^2} \\ &= 1880\ \Omega \end{aligned}$$

**Answer:** 1880 Ω at −57.86°.
:::
:::

::: example
## Summarize ten readings with the statistics module.

::: solution
1. **Call the statistics functions.** Each summary is one call.

```
import statistics as st
x = [4.98, 5.02, 5.01, 4.97, 5.03, 5.00, 4.99, 5.04, 4.96, 5.00]
print(st.mean(x), st.median(x), st.stdev(x))
```

2. **Read the results.** A mean of 5.0, a median of 5.0 and a standard deviation of 0.0258.
3. **Compare with lesson 12.** These are the hand-written formulas from lesson 12, now one call each.

**Answer:** the mean is 5.0, the median 5.0 and the standard deviation 0.0258.
:::
:::

::: check
kind: python
given: ratio = 2 | 10 | 50 | 0.5

## Using `math.log10`, write `db(power_ratio)` returning $10\log_{10}$ of a power ratio. Set `g = db(ratio)` for `ratio` = {ratio}.

```python starter
import math

def db(power_ratio):
    return power_ratio

g = db(ratio)
print(g)
```

```python solution
import math

def db(power_ratio):
    return 10 * math.log10(power_ratio)

g = db(ratio)
print(g)
```

```python tests
import math
assert abs(db(100) - 20) < 1e-12, "db(100) should be 20."
assert abs(db(2) - 3.0103) < 1e-4, "db(2) should be about 3.01."
assert abs(g - 10 * math.log10(ratio)) < 1e-12, "g doesn't match."
```

::: right
Right. `math.log10` is the base-10 logarithm; `math.log` alone is the natural log.
:::
:::

::: check
kind: python
given: R = 470 | 1000 | 4700; C = 10 | 100; f = 100 | 1000 | 10000

## With `cmath`, set `Z` to the impedance of `R` = {R} Ω in series with `C` = {C} nF at `f` = {f} Hz, then `mag = abs(Z)` and `deg` to its angle in degrees.

```python starter
import cmath, math
Z = R
mag = abs(Z)
deg = 0
print(Z, mag, deg)
```

```python solution
import cmath, math
w = 2 * math.pi * f
Z = R + 1 / (1j * w * C * 1e-9)
mag = abs(Z)
deg = math.degrees(cmath.phase(Z))
print(Z, mag, deg)
```

```python tests
import cmath, math
w = 2 * math.pi * f
Zw = R + 1 / (1j * w * C * 1e-9)
assert isinstance(Z, complex), "Z should be complex: a capacitor's impedance is 1/(jωC), written 1 / (1j * w * C)."
assert abs(Z - Zw) < 1e-9 * abs(Zw), "Z doesn't match R + 1/(jωC). Remember C is in nF."
assert abs(deg - math.degrees(cmath.phase(Zw))) < 1e-9, "deg should be math.degrees(cmath.phase(Z)), which is negative for a capacitor."
```

::: right
Right. Python's complex numbers do A3's arithmetic for you.
:::
:::

::: check
kind: python
given: s = 1 | 7 | 42; n = 5 | 10 | 20

## Seed the generator with `random.seed(s)` (`s` = {s}) and set `draws` to a list of `n` = {n} values from `random.uniform(0.95, 1.05)`, then `m` to their mean using `statistics.mean`.

```python starter
import random, statistics
draws = [1.0] * n
m = 1.0
print(draws, m)
```

```python solution
import random, statistics
random.seed(s)
draws = [random.uniform(0.95, 1.05) for _ in range(n)]
m = statistics.mean(draws)
print(draws, m)
```

```python tests
import random, statistics
random.seed(s)
want = [random.uniform(0.95, 1.05) for _ in range(n)]
assert draws == want, "Seed first with random.seed(s), then draw n values with random.uniform(0.95, 1.05)."
assert abs(m - statistics.mean(want)) < 1e-15, "m should be statistics.mean(draws)."
```

::: right
Right. With the seed set, anyone running this gets exactly your numbers.
:::
:::

::: check
kind: python
given: k = 0..3 int

## Set `med`, `sd` and `rng` to the median, sample standard deviation and range (max minus min) of the starter's readings, using `statistics`.

```python starter
import statistics as st
x = [[4.98, 5.02, 5.01, 4.97, 5.03], [3.31, 3.29, 3.30, 3.35, 3.28, 3.30],
     [12.1, 11.9, 12.0, 12.3], [1.01, 0.99, 1.00, 1.02, 0.98, 1.00, 1.01]][k]
med = sd = rng = 0
print(med, sd, rng)
```

```python solution
import statistics as st
x = [[4.98, 5.02, 5.01, 4.97, 5.03], [3.31, 3.29, 3.30, 3.35, 3.28, 3.30],
     [12.1, 11.9, 12.0, 12.3], [1.01, 0.99, 1.00, 1.02, 0.98, 1.00, 1.01]][k]
med = st.median(x)
sd = st.stdev(x)
rng = max(x) - min(x)
print(med, sd, rng)
```

```python tests
import statistics as st
xs = [[4.98, 5.02, 5.01, 4.97, 5.03], [3.31, 3.29, 3.30, 3.35, 3.28, 3.30],
      [12.1, 11.9, 12.0, 12.3], [1.01, 0.99, 1.00, 1.02, 0.98, 1.00, 1.01]][k]
assert abs(med - st.median(xs)) < 1e-12, "med should be st.median(x)."
assert abs(sd - st.stdev(xs)) < 1e-12, "sd should be st.stdev(x), the sample standard deviation."
assert abs(rng - (max(xs) - min(xs))) < 1e-12, "rng should be max(x) − min(x)."
```

::: right
Right. Three calls replace a dozen lines.
:::
:::

::: check
kind: python
given: target = 2000 | 5500 | 7300 | 12600

## Using `itertools.combinations` on the E12 values from 1 kΩ to 8.2 kΩ in the starter, set `pair` to the two different values whose series sum is closest to `target` = {target} Ω (as a sorted tuple), and `err` to how far that sum is from the target.

```python starter
import itertools
E12 = [1000, 1200, 1500, 1800, 2200, 2700, 3300, 3900, 4700, 5600, 6800, 8200]
pair = (E12[0], E12[1])
err = 0
print(pair, err)
```

```python solution
import itertools
E12 = [1000, 1200, 1500, 1800, 2200, 2700, 3300, 3900, 4700, 5600, 6800, 8200]
pair = min(itertools.combinations(E12, 2), key=lambda p: abs(p[0] + p[1] - target))
pair = tuple(sorted(pair))
err = abs(sum(pair) - target)
print(pair, err)
```

```python tests
import itertools
E = [1000, 1200, 1500, 1800, 2200, 2700, 3300, 3900, 4700, 5600, 6800, 8200]
best = min(abs(a + b - target) for a, b in itertools.combinations(E, 2))
assert isinstance(pair, tuple) and len(pair) == 2 and pair[0] < pair[1] and pair[0] in E and pair[1] in E, "pair should be a sorted tuple of two different E12 values."
assert abs(abs(sum(pair) - target) - best) < 1e-9, f"The best pair's sum is {best} Ω from the target."
assert abs(err - best) < 1e-9, "err is abs(sum(pair) - target)."
```

::: right
Right. `combinations(E12, 2)` yields each pair of different values once, and `min` with a key picks the closest sum. It's the same search you'd do by hand, done exhaustively.
:::
:::

::: check
kind: choice

## After `import math`, which of these raises an error?

- [x] `math.sqrt(-1)`
- [ ] `math.log10(1000)`
- [ ] `math.exp(-50)`
- [ ] `math.atan2(-1, 0)`

::: right
Right. `math` works with real numbers only, so the square root of −1 is a "math domain error". `cmath.sqrt(-1)` gives `1j`.
:::

::: misses
- [2] That's 3.0, a perfectly good real logarithm.
- [3] That's a tiny positive number, about 2 × 10⁻²², not an error.
- [4] `atan2` handles a zero second argument; that's the point of it. It returns −π/2.
:::
:::

::: explain
## Why seed a random number generator in engineering code?

::: model
Seeding makes the sequence of "random" numbers the same every run. That means a simulation or test that uses random values gives repeatable results, so if it fails you can rerun it and see the same failure while you debug, and someone else can reproduce your numbers exactly. When you want genuinely different draws, you change or omit the seed deliberately.
:::
:::

::: practice

::: check
kind: python
given: a = -4 | -9 | -16

## Set `r = cmath.sqrt(a)` for `a` = {a}, and `im` to its imaginary part.

```python starter
import cmath
r = 0
im = 0
print(r, im)
```

```python solution
import cmath
r = cmath.sqrt(a)
im = r.imag
print(r, im)
```

```python tests
import math
assert abs(im - math.sqrt(-a)) < 1e-12, "cmath.sqrt of a negative number is imaginary; .imag gives its imaginary part."
```
:::

::: check
kind: python
given: x = 3 | 5 | 8; y = 4 | 12 | 15

## Set `d = math.hypot(x, y)` and `ang` to `math.degrees(math.atan2(y, x))`.

```python starter
import math
d = ang = 0
print(d, ang)
```

```python solution
import math
d = math.hypot(x, y)
ang = math.degrees(math.atan2(y, x))
print(d, ang)
```

```python tests
import math
assert abs(d - math.hypot(x, y)) < 1e-12 and abs(ang - math.degrees(math.atan2(y, x))) < 1e-12, "Use math.hypot and math.atan2 with math.degrees."
```
:::
:::
