Python Math and Random
The math, statistics and random modules give you ready-made tools for calculations and for random numbers.
Built-in Maths Functions
Some maths tools need no import at all.
| Function | What it does | Example | Result |
|---|---|---|---|
abs(x) | Removes the minus sign | abs(-250) | 250 |
round(x, n) | Rounds to n decimals | round(3.14159, 2) | 3.14 |
pow(x, y) | x to the power y | pow(2, 10) | 1024 |
min() / max() | Smallest / largest | max(4, 9, 2) | 9 |
sum() | Adds everything | sum([5, 10, 15]) | 30 |
divmod(a, b) | Quotient and remainder | divmod(17, 5) | (3, 2) |
Example
minutes = 135
hours, mins = divmod(minutes, 60)
print(f"{hours} h {mins} min")
print(round(2.5), round(3.5))
print(round(1234567, -3))2 h 15 min 2 4 1235000
round() sends exact halves to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. This is called "banker's rounding". For money, look at the decimal module.
The math Module
Example
import math
print(math.sqrt(81))
print(math.ceil(7.1), math.floor(7.9))
print(math.pi)
print(math.factorial(5))
print(math.gcd(24, 36), math.lcm(4, 6))
print(math.hypot(3, 4))
print(math.isclose(0.1 + 0.2, 0.3))9.0 8 7 3.141592653589793 120 12 12 5.0 True
math.isclose() is the safe way to compare floats, because 0.1 + 0.2 == 0.3 is actually False in Python (and most languages).
A Practical Example
Say a class has 47 students and each van seats 12. How many vans do you need?
Example
import math
students = 47
seats = 12
print("Vans needed:", math.ceil(students / seats))
radius = 7
print("Pizza area:", round(math.pi * radius ** 2, 1), "sq inch")Vans needed: 4 Pizza area: 153.9 sq inch
The statistics Module
Example
import statistics as st
marks = [72, 85, 90, 66, 85, 78]
print("Mean:", round(st.mean(marks), 2))
print("Median:", st.median(marks))
print("Mode:", st.mode(marks))
print("Std dev:", round(st.stdev(marks), 2))Mean: 79.33 Median: 81.5 Mode: 85 Std dev: 9.07
For big tables of data, Pandas and NumPy are faster, but statistics is perfect for small lists.
The random Module
random picks numbers and items by chance. The output changes every time you run the program.
| Function | Gives you |
|---|---|
random.random() | A float from 0.0 up to (not including) 1.0 |
random.randint(a, b) | A whole number from a to b, both included |
random.uniform(a, b) | A float between a and b |
random.choice(seq) | One random item |
random.choices(seq, k=n) | n items, repeats allowed |
random.sample(seq, n) | n different items |
random.shuffle(lst) | Mixes a list in place |
Repeatable Results With seed()
If you call random.seed() with a number first, you get the same "random" results every run. This is useful for testing and for teaching. The output below is real, and you will see the same if you use seed 7.
Example
import random
random.seed(7)
print(random.randint(1, 6))
print(random.choice(["tea", "coffee", "lassi"]))
print(random.sample(range(1, 50), 6))
students = ["Ali", "Sara", "Omar", "Hina", "Bilal"]
random.shuffle(students)
print(students)
print(round(random.uniform(10, 20), 2))3 tea [26, 42, 4, 5, 35, 7] ['Sara', 'Hina', 'Bilal', 'Ali', 'Omar'] 10.37
A Lucky Draw
Example
import random
random.seed(2026)
entries = ["Ayesha", "Usman", "Fatima", "Hamza", "Zainab", "Imran"]
winners = random.sample(entries, 3)
for place, name in enumerate(winners, start=1):
print(f"Prize {place}: {name}")Prize 1: Ayesha Prize 2: Fatima Prize 3: Imran
sample() never picks the same person twice. choices() can.
Secure Random Values
The random module is fine for games and simulations, but not for passwords or one-time codes. Use the secrets module for those.
Example
import secrets
otp = f"{secrets.randbelow(1_000_000):06d}"
token = secrets.token_hex(8)
print(len(otp), len(token))6 16
Never use random to make passwords, reset links or OTP codes. Its numbers can be predicted. secrets uses the operating system's secure source of randomness.
Exercise
Exercise
Which call can return 10?
