Menu

Libraries

Random Library

The random library provides subprograms that generate random values. Each call returns a value that you can store in a variable and use in your program.

Random whole numbers

random.randint() takes two arguments: the lowest and highest values. It returns a whole number that can be any value from the lowest to the highest, including both ends. For example, random.randint(4, 9) can return 4, 5, 6, 7, 8 or 9. The first argument is the lowest value and the second is the highest, so the order matters.

This program stores a random bonus between 25 and 75 points and displays it:

import random

bonus = random.randint(25, 75)
print("Bonus points awarded: " + str(bonus))

Output:

Bonus points awarded: 74

Random real numbers

random.random() takes no arguments. It returns a real number from 0.0 up to but not including 1.0, so it may return 0.0 but never exactly 1.0. Since the result is less than 1, you can scale it by multiplying. Multiplying by 3.5 gives a real number from 0.0 up to but not including 3.5. The range always starts at 0.0, so the multiplier sets its width: change the multiplier to get the width you need.

This program produces a random length of fabric up to 3.5 metres:

import random

fabric = random.random() * 3.5
print("Fabric length in metres: " + str(fabric))

Output:

Fabric length in metres: 3.3825873749224855
SubprogramArgumentsValue returned
random.randint()Two: lowest and highestA whole number from lowest to highest, including both ends
random.random()NoneA real number from 0.0 up to but not including 1.0

Practise this