Menu

Random Library

Random outcomes

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.

One value, one meaning

A robot vacuum cleaner picks its next movement with random.randint(1, 4), and its firmware fixes what each code means:

CodeWhat the robot does
1Drive forward one metre
2Turn 90° left
3Turn 90° right
4Reverse 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.

Two moves, two codes

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: 1

Acting 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.

Practise this