Python Modules and pip
A module is a Python file full of code that you can reuse in other programs.
What is a Module?
When programs grow, you split the code into several files. Each .py file is a module. Python also comes with many ready-made modules, called the standard library.
Importing a Module
Example
import math
print(math.sqrt(144))
print(math.pi)
print(math.ceil(4.2))
print(math.floor(4.8))12.0 3.141592653589793 5 4
You write the module name, a dot, and then the function name.
Ways to Import
| Code | How you use it |
|---|---|
import math | math.sqrt(9) |
import math as m | m.sqrt(9) |
from math import sqrt | sqrt(9) |
from math import sqrt, pi | sqrt(9) and pi |
Example
from datetime import date
import random as rnd
today = date(2026, 10, 15)
print(today.year)
print(today.strftime("%d-%m-%Y"))
print(rnd.choice(["heads", "tails"]) in ["heads", "tails"])2026 15-10-2026 True
Avoid from module import *. It brings in every name at once, and you lose track of where things came from.
Useful Built-in Modules
| Module | Used for |
|---|---|
math | Square roots, rounding, pi |
random | Random numbers and choices |
datetime | Dates and times |
os | Files, folders and the operating system |
json | Reading and writing JSON data |
statistics | Mean, median, mode |
Use dir() to see what is inside a module, for example print(dir(math)).
Creating Your Own Module
Save this code in a file called shop.py:
Example
# shop.py
TAX = 0.18
def price_with_tax(price):
return round(price * (1 + TAX))Now, in another file in the same folder, import it:
Example
# main.py
import shop
print(shop.price_with_tax(1000))
print(shop.TAX)1180 0.18
What is pip?
pip is Python's package installer. It downloads packages written by other people from the Python Package Index (PyPI), so you can use them in your code. pip comes with Python.
Run these commands in the terminal, not inside Python:
Example
pip --version
pip install requests
pip list
pip uninstall requests| Command | What it does |
|---|---|
pip install name | Installs a package |
pip install --upgrade name | Updates a package |
pip uninstall name | Removes a package |
pip list | Shows installed packages |
pip freeze > requirements.txt | Saves your package list to a file |
After installing, import the package like any other module:
Example
import requests
response = requests.get("https://example.com")
print(response.status_code)200
If pip is not found, try python -m pip install name (or python3 -m pip on macOS and Linux). For bigger projects, create a virtual environment with python -m venv env so each project keeps its own packages.
Exercise
Exercise
Which line lets you call sqrt(25) directly, without writing math. first?
