Random Library
A stored random value is a random number that has been assigned to a variable so the program can use it again later. Each call to random.randint() or random.random() generates a new value rather than handing back an earlier one, so if you need the same number twice you must keep it in a variable.
A generated number is not kept anywhere on its own, so assign it straight away: opened = random.randint(1850, 2020). From then on opened holds that one number. It can be used in arithmetic, printed, or reused several times, and it stays the same unless you assign something new to the variable.
The two approaches behave very differently:
| Approach | What the program gets |
|---|---|
| Generate once into a variable, then use the variable | The same value every time it is used, so printed figures and totals always agree |
| Call the random function again each time it is needed | A new value on every call, so two parts of the output can disagree |
With a stored value, the opening year printed on screen and the centenary year worked out from it always match, because both come from one generated number.
import random
# one random value kept in a variable
opened = random.randint(1850, 2020)
print("The museum opened in " + str(opened) + ".")
print("Its centenary was in " + str(opened + 100) + ".")Output:
The museum opened in 1962.
Its centenary was in 2062.
Some programs ask a question built from a random number and then reveal the answer. Both parts must use the same number, so generate it once, store it, and use the variable in the question and in the answer. Calling the random function again for the answer would build the question around one number and give the answer for a different one, which makes the puzzle impossible to solve. In a full program the player's answer would be checked between the two lines, which needs selection.
import random
# one stored value, used in the clue and in the answer
number = random.randint(3, 9)
print("Clue: my number squared is " + str(number ** 2) + ".")
print("Answer: my number is " + str(number) + ".")Output:
Clue: my number squared is 81.
Answer: my number is 9. OCR GCSE Computer Science · Random Library