By WebNest Studio Engineering Team
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.
Why it matters
Rounding a price up, drawing a random sample, and calculating an average or a median come up in billing, games, testing and data analysis. These three modules cover them. One point is critical for security: the random module must never be used for passwords or tokens.
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).
Exercise
Print 4.2 rounded up, 4.8 rounded down and the greatest common divisor of 12 and 18 on one line. Then print the median of the list. Finally, show that seeding the random generator with the same value gives the same number again.
Expected output: 5 4 6, 3, True (one per line)
import math
import random
import statistics
# TODO: print ceil of 4.2, floor of 4.8 and gcd of 12 and 18 on one line
values = [3, 1, 4, 1, 5]
# TODO: print the median of values
# TODO: seed with 1 and draw a number, seed with 1 again and draw another,
# then print whether the two numbers are equal
Show hints
- The functions are
math.ceil,math.floorandmath.gcd. - Call
random.seed(1)before eachrandom.random().
Show solution
import math
import random
import statistics
print(math.ceil(4.2), math.floor(4.8), math.gcd(12, 18))
values = [3, 1, 4, 1, 5]
print(statistics.median(values))
random.seed(1)
first = random.random()
random.seed(1)
second = random.random()
print(first == second)
Quick quiz
1. Which module should generate a password-reset token?
- A. random
- B. statistics
- C. math
- D. secrets
Show answer
D. secrets uses a source of randomness that is safe for security purposes. random is predictable.
2. What does math.sqrt(16) return?
- A. 4.0
- B. 4
- C. 8
- D. (4, -4)
Show answer
A. math.sqrt always returns a float.
3. What is the purpose of random.seed(42)?
- A. To make the numbers more random
- B. To make the sequence of random numbers repeatable
- C. To limit numbers to 42
- D. To make random secure
Show answer
B. The same seed gives the same sequence, which is useful in tests and experiments.
Interview questions
What is the difference between the random and secrets modules?
Show answer
random uses a fast pseudo-random algorithm whose output can be reproduced with a seed and, given enough output, predicted. It is right for simulations, games and sampling. secrets draws from the operating system's secure source and is meant for passwords, tokens and keys, where the values must be impossible to guess.
What is the difference between mean, median and mode?
Show answer
The mean is the sum of the values divided by their number. The median is the middle value when they are sorted, or the average of the two middle values. The mode is the value that occurs most often. The median is less affected by extreme values, which is why it is used for figures such as salaries. All three are in the statistics module.
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 in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering