Libraries and your own modules

import, Python's own libraries, and a module file of your own.

F4.5Functions and structured codeGCSE15 min

Covers OCR J277 2.2.3 Additional programming techniques · AQA 8525 3.2.10 Structured programming and subroutines (procedures and functions) · Edexcel 1CP2 6.6.1 Built-in, library and user-devised subprograms

Do this lesson in the simulator

Every program you have written starts with from bugbot import *. That line borrows hundreds of lines of someone else's code, the robot's commands, without you seeing any of it. Code packaged to be used by other programs is a library, and a single Python file of it is a module. This lesson uses Python's own libraries, then has you write a module of your own.

import

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

import math

print(math.sqrt(16))
print(math.pi)
side = 30
print("the diagonal of a 30 cm square is", round(math.sqrt(side ** 2 + side ** 2), 1), "cm")

Run this in the simulator

import math loads Python's maths library. Its functions are then reached through its name: math.sqrt, math.pi. The name in front says where each one came from, so two libraries can both have a function called sqrt without a clash.

Three ways to import

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

import random                     # the whole library, used as random.randint
from math import sqrt, pi         # just these names, used as sqrt and pi
import math as m                  # the whole library under a shorter name

print(random.randint(1, 6), sqrt(2), pi, m.floor(2.7))

Run this in the simulator

from bugbot import * is the second kind with a star in place of the names: every name from the library, straight into your program. It is handy for the robot's commands, which you use constantly, but for most libraries the plain import is clearer, because each call shows where it came from.

Each import line puts different names into the program: a whole library under its own name, chosen names on their own, the library under a short name, or every namethe import linenames it adds to your programimport randomrandomrandint...from math import sqrt, pisqrtpiimport math as mmfloorsqrt...from bugbot import *forwarddistanceled...one name with a library inside
import random and import math as m each add one name, with the whole library behind it, so every call says where it comes from. The from lines copy names straight in, which is shorter to type but hides where each one came from.

Libraries you already know

Library What it gives you Example
bugbot the robot's commands forward(50)
random random numbers random.randint(1, 6)
math square roots, pi, rounding down and up math.sqrt(2)
time the clock time.time()

Using a library means not writing, testing and fixing that code yourself. Someone has already made math.sqrt fast and correct.

Your own module

Any Python file can be a module. Below is a file called moves.py that lives on this page. It has its own from bugbot import * line, because a module gets the robot's commands the same way a program does: by importing them. Every cell on this page can use it with import moves.

# moves.py: driving moves, for any program that imports it
from bugbot import *

def zigzag(length):
    """Drive a zigzag: forward and right, then forward and left."""
    forward(60, distance=length)
    right(60, distance=length)
    forward(60, distance=length)
    left(60, distance=length)

def square(size):
    """Drive a square with sides of size cm, ending where it started."""
    pass

Run a program that uses it:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

import moves

moves.zigzag(15)
print("zigzag done at", position())

Run this in the simulator

The program does not contain zigzag at all. It imported it from moves.py. Change zigzag in the file above, for example make the steps shorter, then run the cell again: the program uses the new version, without being edited.

The program imports moves.py, whose zigzag uses forward, right and left from the bugbot libraryyour programmoves.pybugbotimport movesmoves.zigzag(15)from bugbot import *zigzag(length)square(size)square: yours to finishforward()right()left()position()...length = 15
The program only knows the name moves. It calls zigzag, which lives in moves.py, and zigzag drives with commands that moves.py imported from bugbot. Change zigzag in its file and every program that imports moves gets the new version.

Why write modules?

  • Reuse across programs. Write square once in moves.py, and every program can use it.
  • Shorter programs. The main program says what happens; the module holds how.
  • Share and split the work. One person can own moves.py while others write programs that use it, as long as the functions keep their names and parameters.

This is abstraction from the last lesson, taken one step further: the details are not only in a function, they are in a different file.

Task: use your module

Finish square(size) in moves.py above so it drives a square and ends where it started (replace pass). Then, in the task, import moves and use it to drive a square of 20 cm and then a square of 35 cm. Do not write the square's drives in the task program itself.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

import moves

moves.square(20)

Challenges

  1. Add a function triangle(size) to moves.py and use it from a Try-it cell.
  2. Plan a module sounds.py on paper: list the functions a robot program would want from it, with their parameters.
  3. Use math.hypot to print how far the robot is from where it started after a zigzag.

Past paper questions on this

Real exam questions that test this, each worked through with a program you can run.