Skip to content

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).
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]))     # 4
ConstantValue
math.pi3.141592653589793
math.e2.718281828459045
math.tau6.283185307179586 (2π)
math.infPositive infinity
math.nanNot-a-Number
FunctionReturns
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.
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))       # True

Trig functions work in radians. Convert with radians / degrees.

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)

random generates pseudo-random values. For reproducible results (tests, demos) set a seed first.

FunctionReturns
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.
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 is not cryptographically secure. For passwords, tokens, or keys, use the secrets module instead.

sketch sample never repeats, choices does p5.js
Both draw k items from a population, and they answer different questions. sample draws WITHOUT replacement, like dealing cards: no item can appear twice. choices draws WITH replacement, like rolling a die: repeats are not just possible, they are common. Drawing three from ten with choices produced a repeat in 533 of 2,000 runs -- 26.6 percent. Also shown: the same seed always reproduces the same sequence, which is what makes a random test debuggable.

Descriptive statistics on numeric data, no third-party libraries required.

FunctionReturns
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.
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...
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))
  • Float == is unreliable0.1 + 0.2 != 0.3. Use math.isclose.
  • Trig uses radians, not degrees — convert with math.radians.
  • random.shuffle returns None — it shuffles in place; don’t write x = random.shuffle(x).
  • statistics.mode errors on ties in older versions; multimode returns all top values.
  • Use secrets, not random, for anything security-sensitive.
  • math provides constants (pi, e, tau) and functions for roots, logs, factorials, gcd/lcm, trig, and safe float comparison (isclose).
  • random generates pseudo-random numbers and supports choice, choices, sample, and shuffle; seed it for reproducibility and use secrets for security.
  • statistics computes mean, median, mode, variance, and standard deviation without external libraries.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading