Python Tutorial
The math, random and statistics Modules
Three standard modules cover most everyday numeric work. math provides mathematical functions and constants, random generates pseudo-random numbers and random choices (for simulations, games, sampling and shuffling), and statistics computes averages, spread and other descriptive statistics without installing any library.
This lesson tours each module with practical examples, and explains when to use the secrets module instead of random.
The math Module
Constants math.pi, math.e, math.tau, math.inf and math.nan; rounding with floor, ceil, trunc; powers and logs with sqrt, isqrt, pow, exp, log, log10, log2; trigonometry with sin, cos, tan, radians, degrees, hypot; number theory with factorial, gcd, lcm, comb, perm; and isclose, fsum (accurate float sums) and prod.
The random Module
random() gives a float in [0, 1); uniform(a, b) a float in a range; randint(a, b) an integer including both ends; randrange(start, stop, step); choice(seq) one item; choices(seq, weights, k) with replacement; sample(seq, k) without replacement; shuffle(list) in place; gauss(mu, sigma) normally distributed values. random.seed(n) makes results reproducible — essential for tests and experiments.
random vs secrets
random is predictable by design and must never be used for passwords, tokens or OTPs. Use the secrets module: secrets.token_urlsafe(), secrets.token_hex(), secrets.choice(), secrets.randbelow().
The statistics Module
mean, fmean, median, median_low/median_high, mode, multimode, stdev and variance (sample), pstdev and pvariance (population), quantiles, correlation and linear_regression. For large datasets, NumPy and pandas are faster, but statistics is perfect for small data and scripts.
Examples
The math module
import math
print(math.pi, math.e, math.inf > 10**100)
print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5))
print(math.sqrt(2), math.isqrt(17), math.pow(2, 0.5))
print(math.log(math.e), math.log10(1000), math.log2(1024), math.log(8, 2))
print(round(math.cos(math.radians(60)), 3), math.degrees(math.pi), math.hypot(3, 4))
print(math.factorial(6), math.gcd(48, 18), math.lcm(4, 10), math.comb(5, 2), math.perm(5, 2))
print(0.1 + 0.2 + 0.3, math.fsum([0.1, 0.2, 0.3]), math.prod([2, 3, 4]))
3.141592653589793 2.718281828459045 True
-3 -2 -2
1.4142135623730951 4 1.4142135623730951
1.0 3.0 10.0 3.0
0.5 180.0 5.0
720 6 20 10 20
0.6000000000000001 0.6 24
The random module with a fixed seed
import random
random.seed(42)
print(round(random.random(), 4), round(random.uniform(1, 10), 2))
print(random.randint(1, 6), random.randrange(0, 100, 5))
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))
print(random.choices(colors, weights=[5, 1, 1, 1], k=4))
print(random.sample(range(1, 50), 6))
deck = list(range(1, 11))
random.shuffle(deck)
print(deck)
0.6394 1.23
3 35
green
['red', 'red', 'green', 'red']
[38, 28, 3, 2, 6, 14]
[3, 6, 8, 10, 7, 2, 5, 1, 9, 4]
Secure tokens with secrets
import secrets
import string
token = secrets.token_urlsafe(16)
otp = "".join(secrets.choice(string.digits) for _ in range(6))
print(len(token) > 16, len(otp), otp.isdigit())
print(len(secrets.token_hex(8)), 0 <= secrets.randbelow(10) < 10)
True 6 True
16 True
The statistics module
import statistics as st
marks = [72, 85, 90, 66, 85, 78, 95, 85]
print(st.mean(marks), st.median(marks), st.mode(marks), st.multimode([1, 1, 2, 2, 3]))
print(round(st.stdev(marks), 2), round(st.pstdev(marks), 2), round(st.variance(marks), 2))
print(st.quantiles(marks, n=4))
hours = [1, 2, 3, 4, 5]
scores = [52, 60, 68, 71, 82]
print(round(st.correlation(hours, scores), 3))
slope, intercept = st.linear_regression(hours, scores)
print(round(slope, 2), round(intercept, 2), "predicted for 6h:", round(slope * 6 + intercept, 1))
82 85.0 85 [1, 2]
9.5 8.89 90.29
[73.5, 85.0, 88.75]
0.989
7.1 45.3 predicted for 6h: 87.9
Common Mistakes
- Using random to generate passwords, OTPs or tokens — use secrets.
- Forgetting that randint(a, b) includes b while randrange(a, b) excludes it.
- Using mean on skewed data (salaries) where median is more representative.
- Confusing stdev (sample) with pstdev (population).
Key Points to Remember
- math: constants, rounding, powers/logs, trigonometry, factorial/gcd/comb, fsum/prod/isclose.
- random: random, uniform, randint, choice, choices, sample, shuffle; seed for reproducibility.
- secrets: cryptographically secure tokens and choices.
- statistics: mean, median, mode, stdev/variance, quantiles, correlation, linear_regression.
Practice the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.