2-6 Random Numbers

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:

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:

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:

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:

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:

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:

The uniform() function also returns a random float value but allows you to specify the range of values to select from.  For example:

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:


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:

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!

    1. 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.
    2. Describe the range of possible values that each of the following statements can display, then check your hypothesis using the Python interpreter.
    3. Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it’s run.
    4. 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.