Cambridge pseudocode

Random in Pseudocode

RANDOM() takes no arguments and returns a real number from 0 inclusive up to 1 exclusive. You do not declare it. A die needs a whole number, so the usual move is to stretch that unit interval and then cut it.

How it works

Stretch the interval, then cut. Do not round.

RANDOM() * 6 lands somewhere in 0 up to 6, never quite 6. INT deletes the fraction, so the result is 0, 1, 2, 3, 4 or 5, each from an equal sixth of the line. Add 1 and the die reads 1 to 6. ROUND would be the wrong cut: values just below 6 would become 6, and values just above 0 would become 0, so the two end faces would not get a fair share.

DECLARE Roll : INTEGER
Roll <- INT(RANDOM() * 6) + 1
OUTPUT Roll

A Level also has RAND(x), a real from 0 up to x, not including x. OPENFILE FOR RANDOM is unrelated. That RANDOM is the file mode where records have positions. It is in the 9618 guide, not a call to this function.

In Python

random.random, or randint when you want the die

random.random() is RANDOM(): 0 up to 1. random.randint(1, 6) already includes both ends, so you do not add 1 and you do not call int yourself.

Python
import random

print(random.random())       # 0 up to 1, like RANDOM()
print(random.randint(1, 6))  # 1, 2, 3, 4, 5 or 6

Beyond the exam

It is a sequence, not a coin

The next value is calculated from hidden state inside the generator. Same algorithm, same starting state, same rolls. That is a pseudorandom sequence, which is what Python’s random module is too. It is unpredictable enough for a game and a simulation. It is not a measurement of a physical coin, and it is the wrong tool for a secret. Seeding the generator, so a test can replay the same rolls, is the ordinary next step once you leave the exam.

Run the example in the pseudocode compiler online, or read the matching section of the Cambridge pseudocode guide.