Python Basics: Making Random Choices with random
A practice game might need dice rolls, a selection of exercises, or a shuffled question list. Python’s standard-library random module can supply these choices.
Before you start
These independent examples were tested on Linux with Bash, Python 3.12.14 and Python 3.13.5. No extra packages or environment variables are required. The commands use python3; replace it with python3.13 to run that interpreter.
Each script creates its own seeded Random instance. This keeps its generator state separate from module-level calls. The outputs shown were observed on both tested versions; do not assume these higher-level operations produce identical results across future Python versions. Changing the order or number of random calls also changes later results.
Use random for simulations and practice data. For passwords, reset links, or other security-sensitive tokens, use secrets instead.
Create a fresh working directory in one Bash session:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save the source blocks here with the stated filenames. Avoid random.py, which would shadow the standard-library module. These programs only print results; the source files are the only files to clean up.
Roll a six-sided die
Save as demo_random_1.py:
import random
rng = random.Random(42)
rolls = [rng.randint(1, 6) for _ in range(5)]
print("Rolls:", rolls)
print("All within bounds:", all(1 <= roll <= 6 for roll in rolls))
print("Single possible value:", rng.randint(6, 6))Run it:
python3 demo_random_1.pyOutput:
Rolls: [6, 1, 1, 6, 3]
All within bounds: True
Single possible value: 6randint(1, 6) includes both endpoints. Repeats are expected for independent dice rolls. A fixed seed helps reproduce a demonstration in a controlled environment; the bounds check alone does not establish that a generator is fair.
Pick exercises without replacement
Save as demo_random_2.py:
import random
rng = random.Random(42)
exercises = ["loops", "lists", "functions", "files"]
print("Practice:", rng.sample(exercises, k=2))
print("No exercises:", rng.sample(exercises, k=0))
print("Available:", exercises)
try:
rng.sample(exercises, k=5)
except ValueError:
print("Cannot select more entries than are available")Run it:
python3 demo_random_2.pyOutput:
Practice: ['loops', 'files']
No exercises: []
Available: ['loops', 'lists', 'functions', 'files']
Cannot select more entries than are availablesample() returns a new list without changing the input. It selects entries without replacement. Duplicate values in the input can still produce duplicate values in the result. Requesting zero entries is valid; requesting more entries than available raises the intentionally caught ValueError.
Shuffle a copy of a question list
Save as demo_random_3.py:
import random
rng = random.Random(42)
original = ["Q1", "Q2", "Q3", "Q4"]
session = original.copy()
result = rng.shuffle(session)
print("Session:", session)
print("Original:", original)
print("Return value:", result)
empty = []
rng.shuffle(empty)
print("Empty session:", empty)Run it:
python3 demo_random_3.pyOutput:
Session: ['Q3', 'Q2', 'Q4', 'Q1']
Original: ['Q1', 'Q2', 'Q3', 'Q4']
Return value: None
Empty session: []shuffle() changes a mutable sequence in place and returns None. Keep the list separately instead of assigning that return value as your shuffled list. Copying first preserves the original order. An empty list needs no special handling.
Clean up
In the same Bash session, remove only the files you created, then the empty directory:
rm -- demo_random_1.py demo_random_2.py demo_random_3.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf rmdir reports that the directory is not empty, inspect its contents rather than deleting other files blindly.
References
Acknowledgements
This post was created with assistance from AI.