← Python lessons

Python Import: Modules, from…import and as

A module is a file of Python code you can reuse. The import statement loads one, so you can use its functions, such as math.sqrt().

Python comes with hundreds of modules, called the standard library. Read Defining functions first.

Import a module

Write import and the module name at the top of your file. Then put the module name and a dot before each thing you use from it.

import math

print(math.sqrt(16))
print(math.pi)
print(math.floor(7.9))

math.sqrt is the sqrt function inside the math module. The dot keeps it apart from any sqrt of your own.

Import only some names with from…import

from math import sqrt, pi brings in just those names. You then use them without math. in front.

from math import sqrt, pi

print(sqrt(25))
print(round(pi, 2))

Give a module a shorter name with as

as renames what you import. It saves typing for long module names.

import statistics as stats

scores = [3, 10, 5]
print(stats.mean(scores))
print(stats.median(scores))

stats now means the statistics module. Some libraries have a short name everyone uses, such as import numpy as np.

When an import fails

The name must match the module exactly. A typo stops the program.

import maths  # this line raises ModuleNotFoundError

The module is math, not maths. Packages from outside the standard library, such as numpy, need pip install on your own computer first.

Note: Avoid from math import *. It brings in every name at once, so you can no longer tell where a name came from. It can also replace names you made yourself.

See also: Create your own module, Regex basics.

Your turn

Import mean and median from statistics. Print both for scores on one line.

scores = [2, 9, 4]
# add two lines: import mean and median from statistics, then print both

Expected output

5 4

Practise this in the free Python course, where every exercise checks your code instantly.