Python · Chapter 36 of 45
Random Module
The `random` module produces pseudo-random numbers. Use it for games, sampling and simulations — NOT for security (use `secrets` for that).
Common functions: `random()`, `randint(a,b)`, `choice(seq)`, `shuffle(list)`, `sample(seq, k)`.
Seeding
`random.seed(x)` makes the sequence reproducible — useful for tests.
Security note
For passwords/tokens use `secrets.token_urlsafe(16)`; `random` is predictable.
Example 1 (python)
import random
random.seed(42)
print(random.randint(1, 100))
print(random.choice(["red", "green", "blue"]))Output
82
greenrandint gives an inclusive integer; choice picks from a sequence.
Example 2 (python)
import random
deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)Output
[3, 1, 5, 2, 4]shuffle rearranges a list in place.
Key points
- `random.randint(a, b)` — inclusive integer.
- `random.choice(seq)` — pick one item.
- `random.shuffle(list)` — shuffles in place.
- For security use `secrets`, not `random`.
💡 Note: `random.sample(seq, k)` returns UNIQUE picks — no repeats.
