Random Library
Python cannot make a random number on its own, so it comes with a standard library called random. A library is a collection of ready-made functions, such as random.randint() and random.random(), that you can call whenever a program needs a value it cannot predict in advance.
A library is not switched on automatically. Built-in tools such as print() are always available, but anything stored in a library has to be made available to the program first by writing import random. This is the import statement, and it belongs at the top of the program, above every line that uses the library. Importing once is enough for the whole program, however many times you call random.randint() or random.random() afterwards.
# the library is made available once, at the top
import random
locker = random.randint(1, 60)
print("Your locker number is " + str(locker))Output:
Your locker number is 50The import comes first, so Python knows about the library before the call is reached and the program runs normally. Leave the import out, or put it below the line that uses the library, and Python has no idea what random means. It stops with a NameError, telling you the name is not defined, and nothing is printed.
# the import line has been left out
ticket = random.randint(1, 500)
print(ticket)Output:
NameError: name 'random' is not defined (line 2)So the pattern is always the same: ask for the library at the top, then use its functions freely below.
OCR GCSE Computer Science · Random Library