Random Library
When a program needs two random values, calling a random function twice gives two independent choices: the second call knows nothing about the first, so it takes its value from the full range all over again.
import random
delay1 = random.randint(1, 4)
delay2 = random.randint(1, 4)
print("First bus was late by", delay1, "minutes")
print("Second bus was late by", delay2, "minutes")Output:
First bus was late by 4 minutes
Second bus was late by 1 minutesBecause each call is independent, adding the two results does not spread the chance evenly across the totals. Some totals can be made in several different ways, so they come up more often than others. With each bus delay between 1 and 4 minutes, every pair is just as likely as any other, and there are sixteen pairs in total:
| Total delay | Pairs that make it | Number of pairs |
|---|---|---|
| 2 | 1 + 1 | 1 |
| 3 | 1 + 2, 2 + 1 | 2 |
| 4 | 1 + 3, 2 + 2, 3 + 1 | 3 |
| 5 | 1 + 4, 2 + 3, 3 + 2, 4 + 1 | 4 |
| 6 | 2 + 4, 3 + 3, 4 + 2 | 3 |
| 7 | 3 + 4, 4 + 3 | 2 |
| 8 | 4 + 4 | 1 |
So a total of 5 is four times as likely as a total of 2. Generating random.randint(2, 8) once would instead give every total exactly one chance in seven, a flat pattern with no peak in the middle.
Independence also means repeats. Two separate calls can return the same value, because the function keeps no memory of what it produced before and never avoids an earlier result. Often that is exactly what you want, such as two buses both being 3 minutes late.
Sometimes repeats are not allowed. A teacher giving four different project topics, numbered 1 to 10, to four students must not pick the same number twice, so the program has to check rather than assume:
Going round again until a new value appears needs iteration, and the comparison needs selection; those are separate ideas. What matters here is that a random function never guarantees unique results on its own, so a program that needs distinct values must compare each new one with those already stored and generate again when it is a repeat.
OCR GCSE Computer Science · Random Library