GCSE Computer Science
Python random numbers โ GCSE Computer Science
Why programs need randomness
Games need dice rolls and shuffled cards. Simulations need unpredictable events. Quizzes need a different question order each time. Anywhere a program needs to behave differently on different runs without the user telling it how, that's randomness.
Importing the random module
import random
import random has to be the first thing in the file, before any of the random module's functions are used. It only needs to appear once, at the top.
random.randint(a, b)
import random
dice_roll = random.randint(1, 6)
print(dice_roll)
random.randint(a, b) returns a random whole number between a and b โ and, unlike range(), both ends are included. random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6. Every value has an equal chance.
random.random()
import random
value = random.random()
print(value)
random.random() returns a random decimal between 0.0 and 1.0, including 0.0 but never quite reaching 1.0. It's less common on GCSE papers than randint(), but useful for anything that needs a probability rather than a whole number.
A worked example: dice simulator
import random
roll = random.randint(1, 6)
print("You rolled a", roll)
A worked example: random choice from a list
import random
names = ["Alice", "Bob", "Charlie", "Dana"]
index = random.randint(0, len(names) - 1)
print(names[index])
random.randint(0, len(names) - 1) picks a random valid index for the list โ 0 to len(names) - 1 covers every position, because list indices are zero-based.
Assuming random.randint(1, 6) can return 0 or 7. Both endpoints are inclusive โ it only ever returns 1 through 6. This is the opposite of range(), where the end value is excluded, and exams test the contrast between the two directly.
What examiners actually test
Random number questions usually ask you to state the range of possible values a call to randint() or random() could return, or to write code that uses random numbers to simulate something โ a dice, a coin, a shuffled selection. The inclusive-both-ends rule for randint() is the detail most worth being certain of.
Random numbers are the moment a program stops feeling like a worksheet and starts feeling like a game โ which is exactly why the endpoint-inclusive rule matters, because it's the first thing students get wrong the moment they build something they actually want to work. Python Coach bakes that precision into 195 challenges across 27 lessons, with progress tracking built in. Sixty teaching days free, no payment details required.
Start your school's free trial →