Python math, random & statistics
Three modules cover everyday numeric work:
mathmath— mathematical functions and constants for real numbers.randomrandom— pseudo-random numbers, choices, shuffling, and sampling.statisticsstatistics— descriptive statistics (mean, median, standard deviation).
overview.py
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])) # 4overview.py
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
Constants
| Constant | Value |
|---|---|
math.pimath.pi | 3.141592653589793 |
math.emath.e | 2.718281828459045 |
math.taumath.tau | 6.283185307179586 (2π) |
math.infmath.inf | Positive infinity |
math.nanmath.nan | Not-a-Number |
Common functions
| Function | Returns |
|---|---|
math.sqrt(x)math.sqrt(x) | Square root. |
math.pow(x, y)math.pow(x, y) | xx to the power yy (as a float). |
math.floor(x)math.floor(x) / math.ceil(x)math.ceil(x) | Round down / up to an integer. |
math.trunc(x)math.trunc(x) | Drop the fractional part. |
math.factorial(n)math.factorial(n) | n!n! |
math.gcd(a, b)math.gcd(a, b) / math.lcm(a, b)math.lcm(a, b) | Greatest common divisor / least common multiple. |
math.exp(x)math.exp(x) / math.log(x, base)math.log(x, base) | e^x / logarithm. |
math.isclose(a, b)math.isclose(a, b) | Safe float comparison. |
math.comb(n, k)math.comb(n, k) / math.perm(n, k)math.perm(n, k) | Combinations / permutations count. |
math_funcs.py
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)) # Truemath_funcs.py
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
Trig functions work in radians. Convert with radiansradians / degreesdegrees.
trig.py
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)trig.py
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
randomrandom generates pseudo-random values. For reproducible results (tests, demos) set a seed first.
| Function | Returns |
|---|---|
random.random()random.random() | A float in [0.0, 1.0)[0.0, 1.0). |
random.uniform(a, b)random.uniform(a, b) | A float in [a, b][a, b]. |
random.randint(a, b)random.randint(a, b) | An integer in [a, b][a, b] (inclusive). |
random.randrange(stop)random.randrange(stop) | An integer like rangerange. |
random.choice(seq)random.choice(seq) | One random element. |
random.choices(seq, k=n)random.choices(seq, k=n) | nn elements with replacement (weights allowed). |
random.sample(seq, k=n)random.sample(seq, k=n) | nn unique elements without replacement. |
random.shuffle(list)random.shuffle(list) | Shuffle a list in place. |
random.seed(n)random.seed(n) | Make results reproducible. |
random_funcs.py
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))random_funcs.py
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))
randomrandomis not cryptographically secure. For passwords, tokens, or keys, use thesecretssecretsmodule instead.
The statistics module
Descriptive statistics on numeric data, no third-party libraries required.
| Function | Returns |
|---|---|
statistics.mean(data)statistics.mean(data) | Arithmetic average. |
statistics.median(data)statistics.median(data) | Middle value. |
statistics.mode(data)statistics.mode(data) | Most common value. |
statistics.stdev(data)statistics.stdev(data) | Sample standard deviation. |
statistics.pstdev(data)statistics.pstdev(data) | Population standard deviation. |
statistics.variance(data)statistics.variance(data) | Sample variance. |
statistics.harmonic_mean(data)statistics.harmonic_mean(data) | Harmonic mean. |
stats.py
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...stats.py
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
dice_simulation.py
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))dice_simulation.py
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
- Float
====is unreliable —0.1 + 0.2 != 0.30.1 + 0.2 != 0.3. Usemath.isclosemath.isclose. - Trig uses radians, not degrees — convert with
math.radiansmath.radians. random.shufflerandom.shufflereturnsNoneNone— it shuffles in place; don’t writex = random.shuffle(x)x = random.shuffle(x).statistics.modestatistics.modeerrors on ties in older versions;multimodemultimodereturns all top values.- Use
secretssecrets, notrandomrandom, for anything security-sensitive.
Practice Exercises
Exercise 1 – Square root and rounding
Exercise 2 – Reproducible dice roll
Exercise 3 – Average of a list
Summary
mathmathprovides constants (pipi,ee,tautau) and functions for roots, logs, factorials, gcd/lcm, trig, and safe float comparison (iscloseisclose).randomrandomgenerates pseudo-random numbers and supportschoicechoice,choiceschoices,samplesample, andshuffleshuffle; seed it for reproducibility and usesecretssecretsfor security.statisticsstatisticscomputes mean, median, mode, variance, and standard deviation without external libraries.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
