Libraries
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.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.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
| Subprogram | Arguments | Value returned |
|---|---|---|
random.randint() | Two: lowest and highest | A whole number from lowest to highest, including both ends |
random.random() | None | A real number from 0.0 up to but not including 1.0 |
Edexcel GCSE Computer Science · Libraries