Python Tutorial menu

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

python
import math

print(math.sqrt(144))
print(math.pi)
print(math.ceil(4.2))
print(math.floor(4.8))
Output
12.0
3.141592653589793
5
4

You write the module name, a dot, and then the function name.

Ways to Import

CodeHow you use it
import mathmath.sqrt(9)
import math as mm.sqrt(9)
from math import sqrtsqrt(9)
from math import sqrt, pisqrt(9) and pi

Example

python
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"])
Output
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

ModuleUsed for
mathSquare roots, rounding, pi
randomRandom numbers and choices
datetimeDates and times
osFiles, folders and the operating system
jsonReading and writing JSON data
statisticsMean, 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

python
# 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

python
# main.py
import shop

print(shop.price_with_tax(1000))
print(shop.TAX)
Output
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

bash
pip --version
pip install requests
pip list
pip uninstall requests
CommandWhat it does
pip install nameInstalls a package
pip install --upgrade nameUpdates a package
pip uninstall nameRemoves a package
pip listShows installed packages
pip freeze > requirements.txtSaves your package list to a file

After installing, import the package like any other module:

Example

python
import requests

response = requests.get("https://example.com")
print(response.status_code)
Output
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?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp