Menu

Random Library

Random number generation

Random number generation is when a program produces a value that cannot be predicted in advance. The value can change from run to run, so neither the programmer nor the user knows what it will be until the program produces it.

Why randomness is useful

Most values in a program are fixed by the code or typed in by the user, so the same input always leads to the same result. A random value breaks that pattern, which makes a program feel fresh and fair. If a library book was always placed on the same shelf, a reader would learn the answer after one visit; if the shelf is chosen at random, every visit is a genuine search.

Random values are generated inside the program itself, so they are unpredictable rather than just unknown. Two runs can even produce the same value by chance, because random does not mean it never repeats. To act on what the value means, such as choosing a different shelf, the program needs selection, which is covered separately.

RunProgram with a fixed valueProgram with a random value
1stBook on shelf 3Book on shelf 7
2ndBook on shelf 3Book on shelf 2
3rdBook on shelf 3Book on shelf 7

Where random numbers are used

Use a random number wherever an outcome should be decided by chance rather than by a rule: shuffling a playlist so a different song comes first each time, handing out seat numbers for a school concert, picking which pupil answers the next question from the class list, choosing a different warm-up task each lesson, or giving each takeaway order a random order number. In every case a fixed value would give the same result every time, while a user-entered value would not be chance at all.

Python gets its random numbers from the random library. A program creates a random number and can then use that value, for example to display a seat number.

import random

# Each run picks a different seat number for the concert
seat = random.randint(1, 120)
print("Your seat number is " + str(seat))

Output:

Your seat number is 100

Each time this program runs, a new seat number is chosen, though by chance it could match an earlier one. That is exactly what you want for concert seating: nobody can work out in advance which seat they will be given.

Practise this