The random moduleΒΆ
We often want to use random numbers in programs. Here are a few typical uses:
- To play a game of chance where the computer needs to throw some dice, pick a number, or flip a coin,
- To shuffle a deck of playing cards randomly,
- To simulate possible rainfall when we make a computerized model for estimating the environmental impact of building a dam,
- For encrypting your banking session on the Internet.
Python provides a module random
that helps with tasks like this.
Press the run button a number of times. Note that the values change each time. These are random numbers.
- The
randrange
function generates an integer between its lower and upper argument, using the same semantics asrange
- All the values have an equal probability of occurring (i.e. the results are uniformly distributed).
- The
random()
function returns a floating point number in the range [0.0, 1.0) - It is usual to scale the results after calling this method, to get them into a range suitable for your application.
- In the case shown here, we’ve converted the result of the method call to a number in the range [0.0, 5.0).
It is important to note that random number generators are based on a deterministic algorithm — repeatable and predictable. So they’re called pseudo-random generators — they are not genuinely random. They start with a seed value. Each time you ask for another random number, you’ll get one based on the current seed attribute, and the state of the seed (which is one of the attributes of the generator) will be updated. The good news is that each time you run your program, the seed value is likely to be different meaning that even though the random numbers are being created algorithmically, you will likely get random behavior each time you execute.