Functions & Modules
Modules, Packages & the Standard Library
Organise code into modules, import in different ways, use if name == "main", install packages with pip, and tour the standard library: math, random, datetime, os, collections and more.
A module is simply a .py file. Any Python file can be imported by another, giving you its functions, classes and variables.
PI = 3.14159
def circle_area(r):
return PI * r * r
def rectangle_area(l, w):
return l * w
if __name__ == "__main__":
print("This runs only when geometry.py is executed directly")import geometry
from geometry import rectangle_area
import geometry as geo
print(geometry.circle_area(2))
print(rectangle_area(3, 4))
print(geo.PI)12.56636 12 3.14159
(The demo message in geometry.py did not print, because the module was imported, not run.)
Ways to import
| Form | Use as |
|---|---|
import math |
math.sqrt(2) |
import numpy as np |
np.array(...) — an alias |
from math import sqrt, pi |
sqrt(2), pi |
from math import * |
everything — avoid: unclear where names come from |
if name == "main"
Every module has a __name__. When a file is run directly, its __name__ is "__main__"; when it is imported, __name__ is the module's name. Putting test or demo code under this check lets a file work both as a script and as a library.
Packages and pip
A package is a folder of modules (with an __init__.py). Third-party packages are installed from PyPI with pip:
pip install requests # install a package
pip install numpy pandas # several at once
pip list # what is installed
python3 -m venv .venv # create an isolated virtual environmentTour of the standard library
import math, random, datetime, statistics
print(math.sqrt(144), math.factorial(10), math.gcd(84, 36), math.comb(5, 2))
print(round(math.pi, 4), math.ceil(4.1), math.floor(-4.1), math.log2(1024))
random.seed(7) # same "random" numbers on every run
print(random.randint(1, 6), random.choice(["heads", "tails"]))
deck = list(range(1, 11))
random.shuffle(deck)
print(deck, random.sample(range(100), 3))
print(statistics.mean([70, 85, 90]), statistics.median([3, 1, 4, 1, 5]))
today = datetime.date(2026, 11, 14)
exam = datetime.date(2026, 12, 10)
print((exam - today).days, "days to the exam")
print(today.strftime("%d %B %Y, %A"))12.0 3628800 12 10 3.1416 5 -5 10.0 3 heads [8, 6, 4, 3, 9, 5, 10, 2, 1, 7] [64, 27, 4] 81.66666666666667 3 26 days to the exam 14 November 2026, Saturday
from collections import Counter, deque, defaultdict, OrderedDict
import itertools, string
print(Counter("abracadabra").most_common(3))
print(list(itertools.permutations([1, 2, 3], 2)))
print(list(itertools.combinations("ABCD", 2)))
print(list(itertools.accumulate([1, 2, 3, 4]))) # running totals
print(string.ascii_uppercase[:5], string.digits)[('a', 5), ('b', 2), ('r', 2)]
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
[1, 3, 6, 10]
ABCDE 0123456789| Module | Useful for |
|---|---|
math |
maths functions and constants |
random |
random numbers, shuffling, sampling |
datetime, time |
dates, times, timing code |
os, pathlib, shutil |
files, folders, paths |
sys |
command-line arguments, interpreter settings |
collections |
Counter, deque, defaultdict, namedtuple |
itertools |
permutations, combinations, infinite iterators |
json, csv |
reading and writing data formats |
re |
regular expressions |
statistics |
mean, median, mode, standard deviation |
Test yourself
4 questions · pick an answer to check it instantly
- 1
What is
__name__when a module is imported?It is"__main__"only when the file is run directly. - 2
After
from math import sqrt, how do you call it?from … importbrings the name straight into your namespace. - 3
Which command installs a third-party package?
pip downloads packages from the Python Package Index (PyPI). - 4
Which module gives you
Counteranddeque?collectionsprovides specialised container types.