Library Modules: random, math, time and turtle
A library module is a collection of subprograms that Python does not load by default. The PLS names four library modules you must know: random, math, time and turtle. Before you can use any subprogram from a module, you must import it with a line such as import random. Once imported, every subprogram from that module is called using the module’s name, a dot, and the subprogram name — for example random.randint (1, 6) or math.pi.
Every library module must be imported before use, with a line such as import random, import math, import time or import turtle written once near the top of the program. Forgetting the import is a common runtime error — Python will not recognise random.randint if random was never imported.
The random Module
The random module generates numbers for dice games, guessing games and other unpredictable outcomes. random.randint (<a>, <b>) returns a random integer between <a> and <b> inclusive — both endpoints can be chosen. random.random () returns a random real number between 0.0 and 1.0. The values placed inside the brackets of a subprogram call, such as the 1 and 6 in random.randint (1, 6), are called arguments.
import random roll = random.randint(1, 6) print(roll)
A guessing game combines random.randint with a while loop and selection from earlier lessons. The program picks a secret number once, then repeatedly asks the user to guess until they get it right, giving a ‘too low’ or ‘too high’ hint each time.
This program picks a secret number from 1 to 10, then loops until the guess matches. Every construct except import random and random.randint was covered in earlier lessons.
import random
secret = random.randint(1, 10)
guess = int(input("Guess a number from 1 to 10: "))
while guess != secret:
if guess < secret:
print("Too low")
else:
print("Too high")
guess = int(input("Guess again: "))
print("Correct!")random.randint (<a>, <b>) is inclusive at both ends, so a six-sided dice needs random.randint (1, 6), not random.randint (1, 7) or random.randint (0, 6). Using the wrong range is a common mistake that produces the wrong number of possible outcomes.
The math Module
The math module supplies rounding and geometry tools. math.ceil (<x>) returns the smallest integer greater than or equal to <x> — so math.ceil(4.3) gives 5. math.floor (<x>) returns the largest integer less than or equal to <x> — so math.floor(4.7) gives 4. math.pi is a constant holding the value of pi, ready to use in area and circumference formulas.
import math radius = 5 area = math.pi * radius ** 2 print(round(area, 2))
Take care with negative numbers. math.floor (<x>) always rounds down towards negative infinity, and so does the integer division operator // from an earlier lesson — they agree with each other, not with simple truncation towards zero. math.floor(-3.5) and -7 // 2 both give -4, even though truncating towards zero would suggest -3.
Pausing a Program with time.sleep
time.sleep (<sec>) pauses the program for the number of seconds given as its parameter. It is used to slow down a countdown, space out repeated output, or add a pause between turtle movements so an animation is visible rather than appearing instantly.
import time
count = 5
while count > 0:
print(count)
time.sleep(1)
count = count - 1
print("Go!")Turtle Graphics
The turtle module draws lines and shapes by moving a turtle around a canvas. Create the window with turtle.Screen () and resize it with <window>.setup (<width>, <height>) if needed, though the default window size works for most drawings. Create the turtle itself with <turtle> = turtle.Turtle (). The subprograms below are grouped by what they control.
- Movement:
<turtle>.forward (<steps>)moves forward;<turtle>.back (<steps>)moves backward. - Turning:
<turtle>.left (<degrees>)turns counterclockwise;<turtle>.right (<degrees>)turns clockwise. - Pen control:
<turtle>.penup ()lifts the pen so moving does not draw;<turtle>.pendown ()puts it back down;<turtle>.pencolor (<colour>)sets the line colour. - Filling: set
<turtle>.fillcolor (<colour>), call<turtle>.begin_fill ()just before drawing the shape, then call<turtle>.end_fill ()once the shape is complete. - Speed and visibility:
<turtle>.speed (<value>)sets how fast the turtle moves;<turtle>.hideturtle ()and<turtle>.showturtle ()control whether it is drawn. - Finishing:
turtle.done ()keeps the window open at the end of the program until it is closed manually.
The worked example below combines several of these subprograms with a for loop from an earlier lesson to draw and fill a square. Turning through 90 degrees four times and moving forward the same distance each time traces out the four equal sides.
Only one begin_fill () and one end_fill () are needed — the fill colour applies to everything drawn between them, even across four repeats of the loop.
import turtle
t = turtle.Turtle()
t.fillcolor("blue")
t.begin_fill()
for side in range(4):
t.forward(100)
t.left(90)
t.end_fill()
turtle.done()Common Mistakes
- Forgetting
import random,import math,import timeorimport turtlebefore calling a subprogram from that module. - Calling
random.randintwith the wrong range, such as usingrandom.randint (1, 7)for a six-sided dice instead ofrandom.randint (1, 6). - Using a turtle subprogram that is not in the PLS — only the subprograms listed here are guaranteed to be creditable in the exam.
- Leaving out
turtle.done ()at the end of a drawing program, so the window closes immediately instead of staying open.