Python math, random & statistics
Three modules cover everyday numeric work:
math— mathematical functions and constants for real numbers.random— pseudo-random numbers, choices, shuffling, and sampling.statistics— descriptive statistics (mean, median, standard deviation).
import math, random, statistics
print(math.sqrt(144)) # 12.0
print(random.randint(1, 6)) # a dice roll, e.g. 4
print(statistics.mean([2, 4, 6])) # 4The math module
Section titled “The math module”Constants
Section titled “Constants”| Constant | Value |
|---|---|
math.pi | 3.141592653589793 |
math.e | 2.718281828459045 |
math.tau | 6.283185307179586 (2π) |
math.inf | Positive infinity |
math.nan | Not-a-Number |
Common functions
Section titled “Common functions”| Function | Returns |
|---|---|
math.sqrt(x) | Square root. |
math.pow(x, y) | x to the power y (as a float). |
math.floor(x) / math.ceil(x) | Round down / up to an integer. |
math.trunc(x) | Drop the fractional part. |
math.factorial(n) | n! |
math.gcd(a, b) / math.lcm(a, b) | Greatest common divisor / least common multiple. |
math.exp(x) / math.log(x, base) | e^x / logarithm. |
math.isclose(a, b) | Safe float comparison. |
math.comb(n, k) / math.perm(n, k) | Combinations / permutations count. |
import math
print(math.floor(3.7), math.ceil(3.2)) # 3 4
print(math.factorial(5)) # 120
print(math.gcd(12, 18)) # 6
print(math.log(8, 2)) # 3.0
print(math.comb(5, 2)) # 10
# Never compare floats with == ; use isclose
print(0.1 + 0.2 == 0.3) # False (float rounding!)
print(math.isclose(0.1 + 0.2, 0.3)) # TrueTrigonometry
Section titled “Trigonometry”Trig functions work in radians. Convert with radians / degrees.
import math
print(math.sin(math.pi / 2)) # 1.0
print(math.degrees(math.pi)) # 180.0
print(math.radians(180)) # 3.141592653589793
print(math.hypot(3, 4)) # 5.0 (Euclidean distance)The random module
Section titled “The random module”random generates pseudo-random values. For reproducible results (tests, demos) set a seed first.
| Function | Returns |
|---|---|
random.random() | A float in [0.0, 1.0). |
random.uniform(a, b) | A float in [a, b]. |
random.randint(a, b) | An integer in [a, b] (inclusive). |
random.randrange(stop) | An integer like range. |
random.choice(seq) | One random element. |
random.choices(seq, k=n) | n elements with replacement (weights allowed). |
random.sample(seq, k=n) | n unique elements without replacement. |
random.shuffle(list) | Shuffle a list in place. |
random.seed(n) | Make results reproducible. |
import random
random.seed(42) # reproducible output
print(random.random()) # 0.6394...
print(random.randint(1, 6)) # dice roll
print(random.choice(["a", "b", "c"])) # one element
deck = [1, 2, 3, 4, 5]
random.shuffle(deck) # shuffles in place
print(deck)
print(random.sample(range(1, 50), 6)) # lottery: 6 unique numbers
print(random.choices(["heads", "tails"], weights=[1, 1], k=3))
randomis not cryptographically secure. For passwords, tokens, or keys, use thesecretsmodule instead.
The statistics module
Section titled “The statistics module”Descriptive statistics on numeric data, no third-party libraries required.
| Function | Returns |
|---|---|
statistics.mean(data) | Arithmetic average. |
statistics.median(data) | Middle value. |
statistics.mode(data) | Most common value. |
statistics.stdev(data) | Sample standard deviation. |
statistics.pstdev(data) | Population standard deviation. |
statistics.variance(data) | Sample variance. |
statistics.harmonic_mean(data) | Harmonic mean. |
import statistics
scores = [88, 92, 79, 93, 85, 92]
print(statistics.mean(scores)) # 88.16...
print(statistics.median(scores)) # 90.0
print(statistics.mode(scores)) # 92
print(round(statistics.stdev(scores), 2)) # 5.34
print(statistics.variance(scores)) # 28.57...Putting it together
Section titled “Putting it together”import random
import statistics
random.seed(1)
rolls = [random.randint(1, 6) for _ in range(1000)]
print("mean:", round(statistics.mean(rolls), 2)) # close to 3.5
print("mode:", statistics.mode(rolls))Common pitfalls
Section titled “Common pitfalls”- Float
==is unreliable —0.1 + 0.2 != 0.3. Usemath.isclose. - Trig uses radians, not degrees — convert with
math.radians. random.shufflereturnsNone— it shuffles in place; don’t writex = random.shuffle(x).statistics.modeerrors on ties in older versions;multimodereturns all top values.- Use
secrets, notrandom, for anything security-sensitive.
Practice Exercises
Section titled “Practice Exercises”Exercise 1 – Square root and rounding
Section titled “Exercise 1 – Square root and rounding”Exercise 2 – Reproducible dice roll
Section titled “Exercise 2 – Reproducible dice roll”Exercise 3 – Average of a list
Section titled “Exercise 3 – Average of a list”Summary
Section titled “Summary”mathprovides constants (pi,e,tau) and functions for roots, logs, factorials, gcd/lcm, trig, and safe float comparison (isclose).randomgenerates pseudo-random numbers and supportschoice,choices,sample, andshuffle; seed it for reproducibility and usesecretsfor security.statisticscomputes mean, median, mode, variance, and standard deviation without external libraries.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading