3.2.9 - Random number generation (Python)

3.2.9 - Random number generation (Python)

Random values can make a game or simulation vary between runs. You will generate Python integers in a stated range and use a generated value in ordinary selection and arithmetic.

Generating values in a range

A random integer operation selects one of the permitted whole-number outcomes.

Python's standard random module provides randint(low, high). Import the module before using its name. Both limits are included, so a six-sided die needs the range 1 to 6:

Python
import random
roll = random.randint(1, 6)
print(roll)

The output could be 1, 2, 3, 4, 5 or 6. You can predict the set of possible results, but cannot know which result this call will produce. Repeated calls can return the same value: random does not mean different every time. AQA supplied RANDOM_INT(1,6) also includes both endpoints.

Bounds must match the problem. randint(0, 6) allows an impossible zero face; randint(1, 5) omits face 6. Python also has other random operations with different endpoint rules, so use the stated function's convention. Understanding the internal generation of pseudo-random numbers is not required for this specification.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account