Python’s standard library has three modules for everyday number work. math provides square roots, rounding, trigonometry and counting functions. random picks random numbers and shuffles lists for games and simulations. statistics calculates the mean, median, mode and standard deviation of a data set. This lesson tours the most useful functions in each, plus secrets for security-sensitive randomness.
In this lesson you will learn
- Common
mathfunctions and constants - Rounding with
floor,ceilandtrunc - Comparing floats safely with
math.isclose - Random numbers, choices, shuffling and sampling
- Descriptive statistics, and when to use
secrets
The math Module
import math
print(math.sqrt(144), math.pi, round(math.e, 4))
print(math.floor(7.8), math.ceil(7.2), math.trunc(-7.8))
print(math.pow(2, 10), 2 ** 10)
print(math.factorial(6), math.comb(5, 2), math.perm(5, 2))
print(math.gcd(48, 36), math.lcm(4, 6))
print(round(math.sin(math.radians(30)), 3), round(math.log10(1000)))
print(math.isclose(0.1 + 0.2, 0.3), 0.1 + 0.2 == 0.3)
print(math.hypot(3, 4), math.inf > 10**100)
Output
12.0 3.141592653589793 2.7183
7 8 -7
1024.0 1024
720 10 20
12 12
0.5 3
True False
5.0 True
math.sqrtreturns a float;math.piandmath.eare constants.floorrounds down,ceilrounds up andtruncchops off the decimal part, which rounds toward zero (so -7.8 becomes -7, whilefloor(-7.8)would be -8).math.powalways returns a float; the**operator keeps integers exact.factorial,comb(combinations, “5 choose 2”) andperm(permutations) are handy for probability questions.gcdandlcmgive the greatest common divisor and least common multiple.- Trigonometric functions use radians;
math.radiansconverts from degrees. 0.1 + 0.2 == 0.3isFalsebecause of how floats are stored in binary. Compare floats withmath.isclose. See Python Numbers for more.
random, statistics and secrets
import random
import statistics as st
random.seed(42) # same "random" numbers every run
print(random.random()) # float in [0, 1)
print(random.randint(1, 6), random.randint(1, 6)) # dice, both ends included
print(random.choice(["rock", "paper", "scissors"]))
cards = list(range(1, 11))
random.shuffle(cards)
print(cards)
print(random.sample(range(1, 50), 6)) # 6 unique numbers
marks = [72, 85, 90, 64, 85, 78, 95]
print("mean", round(st.mean(marks), 2), "median", st.median(marks), "mode", st.mode(marks))
print("stdev", round(st.stdev(marks), 2))
import secrets
token = secrets.token_hex(8) # use secrets, not random, for passwords and tokens
print(len(token), "hex characters")
Output
0.6394267984578837
1 6
paper
[9, 2, 8, 7, 5, 1, 6, 3, 10, 4]
[3, 2, 6, 14, 15, 33]
mean 81.29 median 85 mode 85
stdev 10.7
16 hex characters
random.seed(42)fixes the starting point, so the “random” sequence is the same every run. This makes tests and demonstrations repeatable; remove the seed for different results each time.random.random()gives a float from 0 up to (but not including) 1.randint(a, b)includes both ends, unlikerange.choicepicks one item,shufflereorders a list in place, andsamplepicks several different items, like drawing lottery numbers.statistics.mean,medianandmodedescribe the centre of the data;stdevmeasures how spread out it is.- The
randommodule is predictable by design, so never use it for passwords, tokens or anything security related. Thesecretsmodule uses the operating system’s secure random source.
Quick Reference
| Task | Function |
|---|---|
| Square root, power | math.sqrt(x), x ** n |
| Round down / up | math.floor(x), math.ceil(x) |
| Round to n decimals | round(x, n) (built-in) |
| Random integer a..b | random.randint(a, b) |
| Random item / several distinct items | random.choice(seq), random.sample(seq, k) |
| Average, middle value | statistics.mean(data), statistics.median(data) |
| Secure token | secrets.token_hex(n), secrets.token_urlsafe(n) |
Common Mistakes
- Comparing floats with
==; usemath.iscloseor round first. - Expecting
round(2.5)to give 3; Python rounds halves to the nearest even number, so it gives 2. - Forgetting
shufflereturnsNone:cards = random.shuffle(cards)loses the list. - Using
randomfor security instead ofsecrets.
Practice Exercises
Exercise 1. Simulate rolling two dice 1000 times and print how often the total is 7.
Show answer
import random
sevens = sum(1 for _ in range(1000)
if random.randint(1, 6) + random.randint(1, 6) == 7)
print(sevens / 1000) # close to 1/6, about 0.167
Exercise 2. Compute the area of a circle with radius 7, rounded to two decimals.
Show answer
import math
print(round(math.pi * 7 ** 2, 2)) # 153.94
Frequently Asked Questions
Are Python’s random numbers truly random?
No. The random module uses the Mersenne Twister algorithm, which produces numbers that look random but are completely determined by the seed. That is fine for games and simulations, not for security.
Should I use statistics or NumPy?
statistics is built in and ideal for small lists. For large data sets and arrays, NumPy and pandas are much faster, as shown in the machine learning lessons.
Summary
mathoffers roots, rounding, trigonometry, factorials and combinations.- Compare floats with
math.isclose. randomgives repeatable pseudo-random values; seed it for reproducible results.statisticssummarises data;secretsis for passwords and tokens.
Next: Python Type Hints.
