Lesson 03-12: The random module¶

Learning Target: I can use the random module to generate random numbers.

Importing The random Module¶

When you import modules, you should always do so at the beginning of your file, at the very top. The syntax is usually:

import module_name

In this case, our module is named random, so we would use this:

import random

Once we have this code, this gives us access to a bunch of functions that are packaged within the random module. Although there are many, the one we are probably going to use the most is called randint().

Using randint()¶

Using the function random.randint(a,b) will give you a random integer between a and b, inclusive. Here are a few examples. Feel free to re-run them to generate different numbers.

Please note that unlike the range() function, where range(1,10) would not include 10, random.randint(1,10) DOES include the 10.

An Example Of Randomness¶

The following is an example of a bit of code that uses random number generation. This code will continuously roll two imaginary dice until it rolls a double (two of the same number).

Next Section - Unit 3 Pre-Lab Check