Menu

Libraries

Libraries and Import

Built-in subprograms such as print() and len() are part of Python itself, so they are ready to use in every program and do not need to be imported. Library subprograms are stored in a separate library (sometimes called a module) that comes with Python but is not loaded automatically, so you must import the library before you can call them.

Importing a library

An import statement names the library and is usually placed at the top of the program. Importing makes the library's subprograms available; it does not call any of them. The program below imports two libraries, then calls one subprogram from each.

import random
import math

score = random.randint(40, 90)
root = math.sqrt(score)
print(score)
print(root)

Output:

89
9.433981132056603

Dot notation and exact names

After importing, call a library subprogram by writing the library name, a dot, then the subprogram name, for example math.sqrt(). The library name is needed because another library could contain a subprogram with the same name, and it tells Python where to look. Names must be written exactly as defined: math.sqrt() is correct, but math.square_root() and sqrt() are not. A call must also give the right number of arguments in the right order, such as two whole numbers for random.randint(40, 90) and one value for math.sqrt(64); the wrong number of arguments stops the program with an error.

Errors from imports and names

If you forget the import, Python does not recognise the library name, so the program stops with an error. A misspelt library or subprogram name causes an error for the same reason: Python cannot find what you asked for. This program tries to use the math library without importing it.

score = 64
root = math.sqrt(score)
print(root)

Output:

NameError: name 'math' is not defined (line 2)

Practise this