Python · Chapter 16 of 21
Python math, statistics, decimal, random and secrets modules
11 min study · Examples checked with Python 3.14 and 3.15 ·
Chapter 2 covered Python’s built-in numbers and their arithmetic. Real programs soon need more: square roots and rounding rules, an average and a spread, money that adds up to the cent, random data for tests, and tokens that nobody can guess. The standard library has a module for each. This chapter shows when to use which, because picking the wrong one (a float for money, random for a password reset link) produces bugs that look like they work.
math: precise operations and rounding directions
import math
print(math.sqrt(81), math.hypot(3, 4), math.pi) # 9.0 5.0 3.141592653589793
print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5), round(-2.5)) # -3 -2 -2 -2
print(math.isqrt(10**20 + 1), math.comb(21, 3), math.gcd(84, 36)) # 10000000000 1330 12
print(math.isclose(0.1 + 0.2, 0.3), math.isclose(1e-12, 0, abs_tol=1e-9)) # True True
print(math.isfinite(float("inf")), math.isnan(float("nan"))) # False True
floor always rounds down, ceil always up, trunc toward zero, and the built-in round to the nearest value with halves going to the even neighbour. Pick the one your rule describes: “number of pages needed” is ceil(items / per_page), not round. isqrt, comb and gcd work on integers exactly, however large, without passing through floats.
math.isclose compares floats with a relative tolerance by default. Near zero a relative tolerance is useless (nothing is “relatively close” to 0), so pass abs_tol there. Data from outside can contain infinity or NaN (“not a number”), and NaN is not even equal to itself, so check with isfinite before calculating.
statistics: averages and spread
import statistics as st
minutes = [25, 30, 30, 45, 50, 240]
print(st.mean(minutes), st.median(minutes), st.mode(minutes)) # 70 37.5 30
print(round(st.stdev(minutes), 1)) # 83.8
print(st.quantiles(minutes, n=4)) # [28.75, 37.5, 97.5]
print(round(st.correlation([1, 2, 3, 4], [2, 4, 5, 8]), 3)) # 0.981
The one 240-minute session pulls the mean up to 70, while the median, the middle value, stays at 37.5. When data has outliers, report the median, or both. stdev measures spread for a sample (pstdev for a whole population), quantiles splits data into equal groups, and correlation and linear_regression cover simple relationships. For large arrays or heavy number crunching, NumPy and pandas are the usual next step; for everyday summaries, statistics is enough.
decimal: money and other decimal rules
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("19.95")
subtotal = price * 3
vat = (subtotal * Decimal("0.20")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(subtotal, vat, subtotal + vat) # 59.85 11.97 71.82
print(0.1 * 3, Decimal("0.1") * 3) # 0.30000000000000004 0.3
print(Decimal(0.1)) # 0.1000000000000000055511151231257827021181583404541015625
print(Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) # 2.68
Decimal does arithmetic in base ten, so 0.1 * 3 is exactly 0.3. Create decimals from strings or integers: Decimal(0.1) faithfully copies the float’s binary approximation, as the third line shows. quantize rounds to a given number of places with a rule you choose; ROUND_HALF_UP is the “school” rule, and the default ROUND_HALF_EVEN is common in banking.
Where you round matters as much as how. Rounding each invoice line and then adding can differ from adding first and rounding the total; the right choice is a business rule, so find out which one applies and write it down in a test. Formatting a number to two places for display does not round the stored value. The fractions module offers exact rational numbers (Fraction(1, 3)) for the rarer cases where you need them.
random: reproducible data for tests and simulations
import random
rng = random.Random(2026)
topics = ["loops", "functions", "classes", "files"]
first = [rng.choice(topics), rng.randint(1, 6), rng.sample(topics, k=2)]
again = random.Random(2026)
second = [again.choice(topics), again.randint(1, 6), again.sample(topics, k=2)]
print(first == second) # True
deck = topics.copy()
rng.shuffle(deck) # in place, returns None
print(sorted(deck) == sorted(topics)) # True
print(len(rng.choices(topics, weights=[5, 1, 1, 1], k=10))) # 10
A random.Random(seed) object produces the same sequence every time it is given the same seed and the same calls, which is what you want for repeatable tests and simulations. Using your own instance, rather than the module-level functions, keeps other code from disturbing the sequence. randint(a, b) includes both ends while randrange follows range and excludes the stop value. sample picks without repeats, choices picks with repeats and optional weights, and shuffle reorders a list in place.
The same predictability makes random unsuitable for anything secret. Its internal state can be reconstructed from enough outputs, after which every future value is known.
secrets: tokens nobody can guess
import secrets
import string
token = secrets.token_urlsafe(32)
code = f"{secrets.randbelow(1_000_000):06d}"
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(20))
print(len(token), len(code), len(password)) # 43 6 20
print(secrets.compare_digest(code, code)) # True
secrets draws from the operating system’s cryptographic random source. Use it for password reset links, API keys, session identifiers and one-time codes. token_urlsafe(32) takes 32 random bytes and encodes them in URL-safe Base64, which gives 43 characters; the number is bytes of randomness, not length. Keep one-time codes as strings, since f"{n:06d}" preserves leading zeros that an integer would drop. A six-digit code has only a million possibilities, so it needs an expiry time and a limit on attempts too.
Compare a submitted secret with the stored one using secrets.compare_digest, which takes the same time whether the first or the last character differs, so the timing of responses leaks nothing. For identifiers that only need to be unique, not secret, uuid.uuid4() is the usual choice; the UUID generator on this site explains the versions. Never log live tokens.
Practice
Write split_bill(total: str, people: int) -> list[Decimal] that splits an amount into equal shares rounded to cents, giving any leftover cents to the first people so the shares add up exactly to the total. Then write a test helper that uses random.Random(seed) to generate 100 random totals and checks the sum each time.
Answer check: split_bill("100.00", 3) returns [Decimal('33.34'), Decimal('33.33'), Decimal('33.33')]. Work in whole cents (int(Decimal(total) * 100)), use divmod(cents, people), and add one cent to the first remainder shares. With a fixed seed, the generated totals are the same on every run, so a failure can be reproduced.
Summary
math gives exact integer functions and explicit rounding directions; compare floats with isclose. statistics summarizes data; prefer the median when outliers exist. Decimal handles money: build it from strings and round with quantize at the point your rules say. Seeded random.Random gives repeatable data; secrets gives values nobody can predict.