the random module

Python includes a lot of functions by default, like print and input. That’s because these functions are used very often. But if we need a function that isn’t included by default, there are ways to add it to our program.

A module is a collection of code that we can add to our program. There’s a module called random that includes a function that generates random numbers:

import random
print(random.randint(1, 5))
print(random.randint(1, 5))
print(random.randint(1, 5))
4
1
5

First we use the import keyword to add the random module to our program. We can access random’s functions by putting a dot after it. Then we type the function name and any arguments that the function needs. The random.randint function takes two integers and then returns a random integer within the range of the two arguments.

We can store the random number in a variable and then do other things with it:

your_lottery_number = 7
winning_lottery_number = random.randint(1, 1000000)
if your_lottery_number == winning_lottery_number:
    print("Here's a dollar; buy yourself something nice")
else:
    print("Too bad for you; the winning number was", winning_lottery_number)
Too bad for you; the winning number was 492054

previous: exercises next: exercises