The Standard Library
Most languages come with a standard library (sometimes called an API – Application Programming Interface) of functions that perform tasks that programmers commonly need to perform. Some of Python’s standard library functions are built-in to the Python interpreter; for example, input() and range(). As you know, to use one of these functions in your program, you simply call the function. To get a shortlist of the built-in functions in Python, type this command in the Python shell:
>>> dir(__builtins__)
For a list of built-in functions with detailed explanations about how to call them, try this command instead:
>>> help(__builtins__)
Many of Python’s standard library functions are stored in (.py) files called modules that Python uses to group related functions; for example, there is a module called math that stores functions for performing advanced mathematical operations. Unlike the built-in functions, to call a function stored in a module you must include an import statement at the top of your program.
Most games include some element of randomness so that they are not predictable and more fun to play. Today we’ll look at some handy random number generating value-returning functions provided by the random module in Python.
Generating Random Numbers
Random numbers are very useful in games to stop them from getting predictable; for example, to simulate the rolling of dice, or determining how an object in a game will move next. If a game has no random elements, players will eventually memorize all the sequences of actions, making it less fun. Python provides a module called random that includes useful random number generation functions. To import this module so that you can call the functions within it, you must include this line at the top of your program:
1 |
import random |
When you import something in Python, the interpreter will first look in the current directory for a corresponding .py file. If it doesn’t find it, Python will look for the module in its standard library directory. Either way, the module will be loaded into memory and the functions within it will be available to your program.
After importing the random module, if you type:
>>> help(random)
in the Python shell, you will see that this module includes a function called randint() that takes two arguments and returns a random integer between those two arguments (inclusive). Because the randint() function is not built-in to the Python interpreter we need to be clear when we call the function which module it comes from. To do this we use dot notation. In dot notation, the function’s name is preceded by the module name it comes from followed by a dot (.). For example:
1 |
number = random.randint(1,10) |
The code above calls the randint() function in the random module we imported. The arguments 1 and 10 tell the function to generate a random number between 1 and 10, inclusive. When the function returns a value, we assign it to a variable called number so that we can use it later in our program. Here’s a longer example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# This program simulates 10 tosses of a coin. import random def main(): for toss in range(10): # Or: for _ in range(10): # Simulate the coin toss. if random.randint(1, 2) == 1: print('Heads') else: print('Tails') # Call the main function. main() |
As an aside: You may have noticed that the toss variable is never actually used inside the for loop. Rather than thinking of a name for a value that is never used, Python allows us to use a single underscore (_) in its place. So we could change the first line of the for statement to this:
1 |
for _ in range(10): |
There are a few other useful random number generation functions in the random module. The randrange() function works a lot like the range() function we learned about in U2-4. Recall that there are three versions of the range() function that each produce a list of integer values. The randrange() function works the same way but after it creates a list it randomly selects only one value from the list and returns it. For example:
1 2 3 |
print(random.randrange(6)) # displays a number from the list [0, 1, 2, 3, 4, 5] print(random.randrange(1, 7)) # displays a number from the list [1, 2, 3, 4, 5, 6] print(random.randrange(1, 10, 2)) # displays a number from the list [1, 3, 5, 7, 9] |
Sometimes you’ll need to generate a random float value. To generate a random float number from 0.0 up to (but not including) 1.0, use the random() function with no arguments:
1 |
print(random.random()) # displays a number between 0.0 and 0.9999999.. |
The uniform() function also returns a random float value but allows you to specify the range of values to select from. For example:
1 |
print(random.uniform(1.0, 10.0)) # displays a number between 1.0 and 9.999999.. |
The Truth About Random Numbers
You may be surprised to learn that the functions in the random module are not generating truly random numbers. Computers can only generate what are called pseudorandom numbers. Recall that “pseudo” means fake, so pseudorandom numbers are numbers that appear random but really aren’t; they are actually calculated mathematically, but will eventually repeat if you generate a few billion of them.
So why do the examples above seem to produce unique results each time? You might think that each time you run this loop you should see the same 10 “random” numbers being generated:
1 2 |
for _ in range(10): print(random.randint(1,10)) |
What happens is that the computer figures out the number of seconds that have passed since Jan 1, 1970 (an important date in the history of the UNIX Operating System), and uses this value as a seed. A seed is an integer value used to calculate the next random number to be produced.
Still not convinced? You can actually set the seed to a specific value instead of the current time by using the seed() function in the random module. Try running this a few times and see what results you get:
1 2 3 4 |
random.seed(100) for _ in range(10): print(random.randint(1,10)) |
Each time you run this code you’ll get the same 10 numbers! This can be useful if you need to repeat a sequence of “random” numbers in a game – when playing back a demo, for instance.
You Try!
-
- Start a new page in your Learning Journal titled “2-6 Random Numbers“. Carefully read the notes above and in your own words summarize the key ideas from each section.
- Describe the range of possible values that each of the following statements can display, then check your hypothesis using the Python interpreter.
1234print random.randint(1, 20)print random.randrange(1, 20)print random.random()print random.uniform(0.1, 0.5) - Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it’s run.
- Write a program that simulates rolling a die 1000 times. Your program should generate 1000 random integers between 1 and 6 (inclusive), and keep track of the number of 1s, 2s, 3s, 4s, 5s, and 6s that are generated. Display the final counts.