A419 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 19 · Modules and the standard library

Most of the code you need is already written

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?

Name it

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

ModuleForExamples
mathreal mathsqrt, exp, log, log10, sin, atan2, hypot, degrees, radians, isclose, pi, inf
cmathcomplex mathsqrt(-4) → 2j, exp, phase, polar, rect
randomrandom numbersseed, random, uniform, gauss, choice, shuffle
statisticssummariesmean, median, stdev, pstdev
itertoolscombinationsproduct, 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.

Worked example

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

Show the solution
  1. Build the impedance as a complex number. The capacitor adds 1/(jω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°
  1. Convert to polar. cmath.polar returns the magnitude and angle together.
  2. Check by hand. A3's hand calculation gives the same: |Z|=10002+15922=1880Ω

Answer 1880 Ω at −57.86°.

Worked example

Summarize ten readings with the statistics module.

Show the 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))
  1. Read the results. A mean of 5.0, a median of 5.0 and a standard deviation of 0.0258.
  2. 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

Using math.log10, write db(power_ratio) returning 10log10⁡ of a power ratio. Set g = db(ratio) for ratio = 10.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 = 5500 Ω (as a sorted tuple), and err to how far that sum is from the target.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

After import math, which of these raises an error?

Explain why

Why seed a random number generator in engineering code?

Practice

Keep practicing

7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.