The random module is made available to your
program with:
import random
The random module contains the following
functions for working with simple distributions of random numbers. There
are numerous other, more sophisticated distributions available, but some
later exercises will only use these functions.
random.choice (sequence
) → value
chooses a random value from the sequence
sequence. Example: random.choice( ['red',
'black', 'green'] ).
choose a random element from range
(start, stop,
step). Examples:
randrange(6) returns a number, n,
0 ≤ n < 6. randrange(1,7)
returns a number, n, 1 ≤ n
< 7. randrange(10,100,5) returns a number,
n, between 10 and 95 incremented by 5's, 10 ≤
5k < 100.
random.uniform (a,
b ) → number
a random floating point number, r,
a ≤ r <
b.
The randrange has two optional values, making
it particularly flexible. Here's an example of some of the
alternatives.
Example 5.1. demorandom.py
#!/usr/bin/env python
import random
# Simple Range 0 <= r < 6
print random.randrange(6), random.randrange(6)
# More complex range 1 <= r < 7
print random.randrange(1,7), random.randrange(1,7)
# Really complex range of even numbers between 2 and 36
print random.randrange(2,37,2)
# Odd numbers from 1 to 35
print random.randrange(1,36,2)
This demonstrates a number of ways of generating random numbers. It
uses the basic random.randrange with a variety of
different kinds of arguments.
Published under the terms of the Open Publication License