AQA GCSE Computer Science (8525), section 3.2.9 (Random number generation in a programming language)
Why use random numbers?
Programs use random numbers for games (dice, shuffling cards, enemy behaviour), simulations, and picking a random question. You do not need to know how a computer generates random numbers.
In pseudo-code
roll ← RANDOM_INT(1, 6)
OUTPUT roll
RANDOM_INT(1, 6) gives a random whole number from 1 to 6, including both ends.
In Python
import random
roll = random.randint(1, 6) # 1, 2, 3, 4, 5 or 6
print(roll)
colour = random.choice(["red", "green", "blue"])
print(colour)
Example: guessing game
import random
secret = random.randint(1, 10)
guess = int(input("Guess a number from 1 to 10: "))
if guess == secret:
print("Correct!")
else:
print("Wrong, it was", secret)
Example: rolling two dice
import random
total = random.randint(1, 6) + random.randint(1, 6)
print(total)
Two dice give a total from 2 to 12. Note that this is not the same as randint(2, 12), because totals near 7 are more likely.
Getting a random number in a different range
To get a random multiple of 5 from 5 to 50, multiply:
print(random.randint(1, 10) * 5)
Remember
- Say which numbers are included (the range).
- A random number changes each time the program runs, so testing needs care.
Common mistake: getting the range wrong. RANDOM_INT(1, 6) includes both 1 and 6. If you wanted 0 to 5 you would write RANDOM_INT(0, 5). Also, forgetting to import random in Python gives an error.
Exam tip: use RANDOM_INT(low, high) and check that the lowest and highest possible values match what the question needs. For a dice, that is 1 and 6.
Check yourself
Write pseudo-code to simulate rolling a six-sided dice.
roll ← RANDOM_INT(1, 6).
What numbers can RANDOM_INT(0, 3) produce?
0, 1, 2 or 3.
Name one use of random numbers in a program.
Any sensible use, such as a dice roll in a game or picking a random question.