AQA 7517, section 4.1.1.8
Many programs need an element of chance, such as shuffling cards, rolling a dice, picking a quiz question or simulating weather. Programming languages provide random number generation for this.
Using random numbers in Python
Python's random module has a few commonly used functions.
import random
print(random.randint(1, 6)) # whole number 1 to 6, both included
print(random.random()) # real number, 0 up to but not 1
print(random.uniform(1.0, 2.0)) # a real number between 1.0 and 2.0
colours = ["red", "green", "blue"]
print(random.choice(colours)) # one item chosen at random
random.shuffle(colours) # shuffles the list in place
Check the exact range in your language. randint(1, 6) includes both ends in Python, but in many languages the upper limit is excluded, so a dice needs something like random(1, 7).
Scaling to the range you want
A generator often gives a real number from 0 to 1. To get a whole number in a range, scale the number, then truncate it:
import random
r = random.random() # for example 0.73
roll = int(r * 6) + 1 # int(4.38) + 1 = 5
print(roll)
The result of r * 6 is at least 0 and less than 6, so truncating gives 0 to 5, and adding 1 shifts it to 1 to 6.
Is it really random?
A computer follows instructions exactly, so the values from a generator aren't truly random. They come from a mathematical formula that starts from a number called a seed, and the numbers look random but can be reproduced. They are called pseudo-random numbers.
import random
random.seed(42)
print(random.randint(1, 100)) # same number every run with seed 42
By default the seed comes from something unpredictable, such as the system clock, so each run gives different values. Setting a fixed seed is useful when testing, because the program behaves the same way each time.
Worked example
Task: a number-guessing game picks a secret number from 1 to 20. The player gets up to 5 attempts.
import random
secret = random.randint(1, 20)
attempts = 0
guessed = False
while attempts < 5 and not guessed:
guess = int(input("Guess (1-20): "))
attempts = attempts + 1
if guess == secret:
guessed = True
elif guess < secret:
print("Too low")
else:
print("Too high")
if guessed:
print("Correct in", attempts, "tries")
else:
print("The number was", secret)
The random number is generated once, before the loop. If randint were inside the loop, the target would change after every guess.
Check yourself
Why are the numbers from a computer's random generator called pseudo-random?
They are produced by a mathematical formula from a starting value (the seed), not by a truly unpredictable process, so the sequence can be reproduced if you know the seed.
Write a line of Python that simulates rolling a 10-sided dice numbered 1 to 10
random.randint(1, 10)
Why might a programmer set a fixed seed while testing?
So the "random" values are the same every run, which makes the program's behaviour repeatable and easier to debug.