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
| Style | Then use |
|---|---|
import math | math.sqrt(9) |
from math import sqrt | sqrt(9) |
import math as m | m.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 requestsTip: Don't name your own file after a module, like
math.pyorrandom.py. Python would import your file instead of the real module!