The random Module
“Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.”
The random module contains a number of random number generators.
The basic random number generator (after an algorithm by Wichmann and Hill, 1982) can be accessed in several ways, as Example 2-29 shows.
Example 2-29. Using the random Module to Get Random Numbers
File: random-example-1.py
import random
for i in range(5):
# random float: 0.0 <= number < 1.0
print random.random(),
# random float: 10 <= number < 20
print random.uniform(10, 20),
# random integer: 100 <= number <= 1000
print random.randint(100, 1000),
# random integer: even numbers in 100 <= number < 1000
print random.randrange(100, 1000, 2)
0.946842713956 19.5910069381 709 172
0.573613195398 16.2758417025 407 120
0.363241598013 16.8079747714 916 580
0.602115173978 18.386796935 531 774
0.526767588533 18.0783794596 223 344Note that the randint function can return the upper
limit, while the other functions always return values smaller than
the upper limit.
Example 2-30 shows how the choice function picks a random item from a
sequence. It can be used with lists, tuples, or any other sequence
(provided it can be accessed in random order, of course).
Example 2-30. Using the random Module for Random Items from a Sequence
File: random-example-2.py
import random
# random choice from a list
for i in range(5):
print random.choice([1, 2, 3, 5, 9])
2
3
1
9
1In 2.0 and later, the shuffle function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access