Python For GCSE
Random Numbers

We will want to make random numbers in some of our programs. To do this, we need to work with a built-in module called random. We need to import the module to use it.

It would be a mistake to name a python program file with the same name as a Python module. Make sure not to fall into this trap. Your program will not run if you do.

In the first example, we import the random module and use the randint() method to get a random integer from 1 to 10.

import random

a = random.randint(1,10)

The random module has lots of methods. If we only import the one(s) we need, our program can be easier to write.

from random import randint

a = randint(1,10)

If you want to make a random real number, you need to use the random() method. This method returns a random floating point number between 0 and 1.

from random import random

a = random()

To get a random floating point number in a range, you can use the uniform() method.

from random import uniform

a = uniform(10,20)

There are some other methods in the random module that we will want to use. These will be explained on the pages for the programming structures with which they are used.