Sub topic 6
Generating random numbers
The random module generates pseudo-random numbers: values that look unpredictable but come from a deterministic algorithm. This chapter covers the four core functions for producing numbers: random(), randint(), randrange(), and uniform(). It also covers where each one is easy to misuse.
This chapter assumes you can write Python functions and loops, use list comprehensions, and handle exceptions with try/except. Picking from sequences, seeding, and security come in later chapters.
How the module produces numbers
CPython's random module uses the Mersenne Twister algorithm. It produces a long stream of 53-bit floats, and every other function in the module is built on that stream. The stream is fully determined by an internal state, so it is repeatable and fast. It is not secure, because an observer who sees enough output can predict what comes next.
The functions you call as random.randint(...) are bound methods of one hidden, shared random.Random instance. Every call advances that one shared state. You can also create your own Random objects with separate states, which a later chapter covers.
The base function: random()
random.random() returns a float x with 0.0 <= x < 1.0. It can return 0.0 but never 1.0.
import random
x = random.random()
print(0.0 <= x < 1.0) # True
samples = [random.random() for _ in range(10_000)]
print(min(samples) >= 0.0, max(samples) < 1.0) # True True
print(0.45 < sum(samples) / len(samples) < 0.55) # True: the mean is near 0.5You can scale and shift this value yourself. random.random() * 10 gives a float in [0, 10), and 5 + random.random() * 10 gives one in [5, 15). For most tasks, one of the named functions below states your intent more clearly.
Random integers: randint() and randrange()
random.randint(a, b) returns an integer n with a <= n <= b. Both ends are included, which matches how people describe dice: randint(1, 6) can return 1 or 6.
random.randrange(start, stop, step) follows the same rules as range(). It includes start, excludes stop, and accepts an optional step. With one argument, randrange(n) returns an integer from 0 to n - 1.
import random
rolls = [random.randint(1, 6) for _ in range(1000)]
print(min(rolls), max(rolls)) # 1 6 (a miss is astronomically unlikely)
print(random.randrange(10) in range(10)) # True: 0 to 9
print(random.randrange(0, 100, 2) % 2 == 0) # True: only even numbers
print(random.randrange(5, 55, 5) in range(5, 55, 5)) # True: 5, 10, ..., 50randint(a, b) is an alias for randrange(a, b + 1). Use randint when you think in inclusive bounds, and randrange when you want the same behavior as range(), for example to pick a valid list index with randrange(len(items)).
Common integer mistakes
- Off-by-one on the upper bound.
randrange(1, 6)never returns 6. If you meant a die, userandint(1, 6). - Empty ranges.
randrange(5, 5)andrandrange(0)raiseValueErrorbecause there is nothing to choose from. - Non-integer arguments.
randint(1, 6.5)is an error. Convert withint()orround()first, or useuniform()if you need a float. - Hand-rolled scaling.
int(random.random() * 6) + 1works, butrandint(1, 6)is shorter and cannot suffer from a slipped bound.
import random
for call in (lambda: random.randrange(5, 5), lambda: random.randint(1, 6.5)):
try:
call()
except ValueError as exc:
print("ValueError:", exc)Random floats in a range: uniform()
random.uniform(a, b) returns a float between a and b. Every value in the interval is equally likely, which is what "uniform" means. Internally it computes a + (b - a) * random().
import random
temperature = random.uniform(18.0, 24.0)
print(18.0 <= temperature <= 24.0) # True
# The order of the arguments does not matter.
print(-1.0 <= random.uniform(1.0, -1.0) <= 1.0) # TrueThe documentation notes that the end point b may or may not be included, depending on floating-point rounding. Do not write code that relies on either behavior. If you need a strictly half-open interval, build it from random() and check the edge case yourself.
Choosing the right function
| You need | Use | Range |
|---|---|---|
| A float for probabilities or scaling | `random()` | `[0.0, 1.0)` |
| A float in a custom range | `uniform(a, b)` | between `a` and `b` |
| An integer with inclusive bounds | `randint(a, b)` | `a` to `b`, both included |
| An integer like `range()`, with optional step | `randrange(start, stop, step)` | `stop` excluded |
Worked example: a Monte Carlo estimate of pi
A Monte Carlo method estimates a quantity by sampling random points. Here, points are drawn uniformly in the unit square. The fraction that land inside the quarter circle x² + y² <= 1 approaches π/4.
import math
import random
def estimate_pi(samples: int, rng: random.Random) -> float:
inside = 0
for _ in range(samples):
x = rng.random()
y = rng.random()
if x * x + y * y <= 1.0:
inside += 1
return 4 * inside / samples
rng = random.Random(42)
estimate = estimate_pi(100_000, rng)
print(abs(estimate - math.pi) < 0.05) # TrueThe function takes a random.Random instance as a parameter instead of calling the module-level functions. That makes it easy to test with a fixed seed, a technique the seeding chapter explains.
The error of such an estimate shrinks roughly with the square root of the sample count. Quadrupling the samples only halves the typical error, so Monte Carlo methods are good for rough answers and poor for high precision.
Edge cases and gotchas
- Results differ on every run. Never assert an exact random value in a test. Assert properties instead, such as range, type, or length.
- Shared state. All module-level calls draw from one generator. If a library you import also calls
random.random(), the order of values you see can change. A privateRandominstance avoids this. - Extreme ranges.
uniform(a, b)with very large or very close bounds is limited by float precision, since a 53-bit float has finite resolution. - Not for security. The Mersenne Twister is predictable. Do not use these functions for passwords, tokens, or keys. The
secretsmodule covers that, in a later chapter. - Other distributions exist. The module also offers
gauss(mu, sigma)for normally distributed values andtriangular(), among others. Use them when a flat distribution is the wrong model.
Summary
random() gives a float in [0, 1). uniform(a, b) stretches that to any float range. randint(a, b) includes both integer bounds. randrange() behaves like range(), so its upper bound is excluded, and it accepts a step. Most bugs with these functions come from a wrong bound or from testing exact random values.
Exercise
You want to simulate rolling two six-sided dice and report their sum. Write the expression, and explain why random.randrange(1, 6) would be a wrong substitute for one die.
Show answer
Use random.randint(1, 6) + random.randint(1, 6). The result is between 2 and 12. random.randrange(1, 6) excludes its upper bound, so it returns 1 to 5 and can never produce a 6. The correct randrange form is random.randrange(1, 7).
Exercise
Write code that returns a random multiple of 10 between 0 and 100 inclusive, and a random float between -5.0 and 5.0. Which function would you use for each, and why is randrange(0, 100, 10) not enough for the first one?
Show answer
Use random.randrange(0, 101, 10) for the multiple of 10, and random.uniform(-5.0, 5.0) for the float. randrange(0, 100, 10) excludes 100, so it can only return 0 to 90. Setting the stop to 101 includes 100 in the possible results.