Random Library
A random integer can stand for one of several outcomes: you decide, before the program runs, what each possible value will mean. Python supplies only the number, so the meaning comes from your design rather than from the random library.
A robot vacuum cleaner picks its next movement with random.randint(1, 4), and its firmware fixes what each code means:
| Code | What the robot does |
|---|---|
| 1 | Drive forward one metre |
| 2 | Turn 90° left |
| 3 | Turn 90° right |
| 4 | Reverse one metre |
Four codes give four outcomes, so every movement is equally likely. The range must match the number of outcomes: randint(1, 6) would produce two codes the robot has no instruction for. randint includes both ends, so 1 to 4 really does contain four values.
A seating-plan program shows the same rule from the other direction. With eight tables it needs randint(1, 8); writing randint(1, 6) instead would leave tables 7 and 8 unused all year, because those numbers could never come up.
Each move needs its own code, so each call to random.randint() supplies one code. This program keeps both codes in separate variables, so each one can be looked up against the table above.
import random
# two moves in a row for the robot vacuum
move_one = random.randint(1, 4)
move_two = random.randint(1, 4)
print("First move code:", move_one)
print("Second move code:", move_two)Output:
First move code: 4
Second move code: 1Acting on the meaning — turning code 2 into an actual left turn inside the program — needs a decision. That is selection, covered elsewhere. The mapping is fixed in advance: the random call supplies the number, and the design supplies what it stands for.
OCR GCSE Computer Science · Random Library