Reading history

Python math, random and statistics Modules

4 min read 0 views

Learn Python's math module (sqrt, floor, ceil, isclose, comb), random (seed, randint, choice, shuffle, sample), statistics (mean, median, stdev) and secrets.

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 math functions and constants
  • Rounding with floor, ceil and trunc
  • 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.sqrt returns a float; math.pi and math.e are constants.
  • floor rounds down, ceil rounds up and trunc chops off the decimal part, which rounds toward zero (so -7.8 becomes -7, while floor(-7.8) would be -8).
  • math.pow always returns a float; the ** operator keeps integers exact.
  • factorial, comb (combinations, “5 choose 2”) and perm (permutations) are handy for probability questions. gcd and lcm give the greatest common divisor and least common multiple.
  • Trigonometric functions use radians; math.radians converts from degrees.
  • 0.1 + 0.2 == 0.3 is False because of how floats are stored in binary. Compare floats with math.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, unlike range.
  • choice picks one item, shuffle reorders a list in place, and sample picks several different items, like drawing lottery numbers.
  • statistics.mean, median and mode describe the centre of the data; stdev measures how spread out it is.
  • The random module is predictable by design, so never use it for passwords, tokens or anything security related. The secrets module uses the operating system’s secure random source.

Quick Reference

TaskFunction
Square root, powermath.sqrt(x), x ** n
Round down / upmath.floor(x), math.ceil(x)
Round to n decimalsround(x, n) (built-in)
Random integer a..brandom.randint(a, b)
Random item / several distinct itemsrandom.choice(seq), random.sample(seq, k)
Average, middle valuestatistics.mean(data), statistics.median(data)
Secure tokensecrets.token_hex(n), secrets.token_urlsafe(n)

Common Mistakes

  1. Comparing floats with ==; use math.isclose or round first.
  2. Expecting round(2.5) to give 3; Python rounds halves to the nearest even number, so it gives 2.
  3. Forgetting shuffle returns None: cards = random.shuffle(cards) loses the list.
  4. Using random for security instead of secrets.

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

  • math offers roots, rounding, trigonometry, factorials and combinations.
  • Compare floats with math.isclose.
  • random gives repeatable pseudo-random values; seed it for reproducible results.
  • statistics summarises data; secrets is for passwords and tokens.

Next: Python Type Hints.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *