bhylu.com

Advertisements

Random Module

The random module supplies pseudo-random choices for simulations, games, and sampling. It is not designed for passwords or security tokens.

Understand the idea

A separate Random instance keeps a demonstration's state independent from other code using the module-global generator. A fixed seed helps reproduce a test in a known environment, but it does not make a simulation representative of real-world observations. Use secrets for suitable security-sensitive randomness.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

from random import Random
rng = Random(24)
print(rng.choice(["HTML", "CSS", "Python"]))
print(len(rng.sample(range(20), 4)))

Read the result

The first value is one chosen course, and the sample has four distinct members. The fixed seed makes the sequence repeatable in the tested environment.

Try one change

Generate two separate seeded Random instances and compare their first few results.