Understand pseudorandom numbers from the random module.
What It Does and Why It Matters
random uses a deterministic Mersenne Twister generator for simulation, games, sampling, and reproducible tests. It must not generate passwords, access tokens, or cryptographic secrets; use the secrets module for security-sensitive randomness.
A dedicated Random instance helps isolate reproducible simulations from global generator state.
Pseudorandom examples are suitable for simulation and tests. Use secrets instead for tokens, passwords and authentication.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import random
random_generator = random.Random(2026)
print(random_generator.randint(1, 6))
print(random_generator.choice(['red', 'blue', 'green']))
How the Code Works
- The imports make these standard-library tools available: random.
- The name random_generator receives the value of random.Random(2026). Changing this input lets you explore a different case.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
1
blue
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Create a seeded dice simulator and compare repeated runs.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Generating security tokens using random() instead of secrets or a cryptographically secure generator.
- Overlooking the documented condition: it must not generate passwords, access tokens, or cryptographic secrets; use the secrets module for security-sensitive randomness.
Key Takeaways
- Understand pseudorandom numbers from the random module.
- random uses a deterministic Mersenne Twister generator for simulation, games, sampling, and reproducible tests.
- Create a seeded dice simulator and compare repeated runs.
- Pseudorandom examples are suitable for simulation and tests. Use secrets instead for tokens, passwords and authentication.