Using Modules: import

What is a module?

A module is a file full of ready-made code that someone has already written for you. Python comes with hundreds of them – this is called the standard library.

Think of it like this: Modules are like toolboxes. You don't build a hammer every time you need one – you open the toolbox and take it out.

import

import math

print(math.sqrt(81))
print(math.pi)

Output

9.0
3.141592653589793

After import math, everything in the module is reached with a dot: math.sqrt, math.pi.

Importing just what you need

from math import sqrt, pi

print(sqrt(16))
print(round(pi, 3))

Output

4.0
3.142

Giving a module a short name

import datetime as dt

new_year = dt.date(2027, 1, 1)
print(new_year.strftime("%d %B %Y"))

Output

01 January 2027
StyleThen use
import mathmath.sqrt(9)
from math import sqrtsqrt(9)
import math as mm.sqrt(9)

Installing more modules

Thousands of extra modules (called packages) are available online. On your own computer you install them with pip, for example the popular requests package for talking to websites:

pip install requests

Tip: Don't name your own file after a module, like math.py or random.py. Python would import your file instead of the real module!

HOME LEARN COMMUNITY DASHBOARD