Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 11 of 22 · 4 min read

Python modules, packages and pip

Python modules notes: three ways to import, the math, random and datetime modules, making your own module, and installing packages with pip, with examples.

Modules: toolboxes you can import

A module is a Python file full of ready-made functions and values. Python ships with hundreds of them (the *standard library*), and you can install thousands more.

  • A module is one .py file.
  • A package is a folder of modules.
  • pip is the tool that downloads and installs packages from the internet.

Three ways to import

import math                       # 1. the whole module; use math.sqrt()
print(math.sqrt(49))

from math import sqrt, pi         # 2. only some names; use sqrt() directly
print(sqrt(49), pi)

import datetime as dt             # 3. a short nickname (alias)
print(dt.date.today())

Avoid from math import *: it pulls in every name and can silently replace your own variables.

The math module

FunctionExampleResult
math.sqrt(x)math.sqrt(81)9.0
math.pow(x, y)math.pow(2, 5)32.0
math.ceil(x)math.ceil(4.1)5
math.floor(x)math.floor(4.9)4
math.factorial(n)math.factorial(5)120
math.pi3.14159...
import math
r = 7
print(f"Area of the circle: {math.pi * r ** 2:.2f}")

The random module

import random
print(random.randint(1, 6))               # dice roll: 1 to 6, both included
print(random.random())                    # a float from 0.0 up to (not including) 1.0
print(random.choice(["Asha", "Ravi"]))    # one random item
names = ["A", "B", "C", "D"]
random.shuffle(names)                     # shuffles the list in place
print(random.sample(range(1, 50), 6))     # 6 different numbers

Example: a 4-digit OTP.

otp = random.randint(1000, 9999)
print("Your OTP is", otp)

The datetime module

from datetime import date, datetime

today = date.today()
print(today)                              # 2026-10-29
print(today.strftime("%d/%m/%Y"))         # 29/10/2026

exam = date(2027, 3, 1)
print((exam - today).days, "days left")   # subtracting dates gives a timedelta

now = datetime.now()
print(now.strftime("%I:%M %p"))           # 05:42 PM

Make your own module

Save functions in a file, for example school_utils.py:

# school_utils.py
def grade(marks):
    return "Pass" if marks >= 33 else "Fail"

SCHOOL = "Model School"

Then import it from another file in the same folder:

# main.py
import school_utils
print(school_utils.grade(45), school_utils.SCHOOL)

if __name__ == "__main__"

Code at the bottom of a module runs when the module is imported. To run test code only when the file is run directly, put it under this check:

if __name__ == "__main__":
    print(grade(50))      # runs for 'python school_utils.py', not for 'import school_utils'

pip: install packages from the internet

Run pip in a terminal (Command Prompt), not inside Python:

pip install tabulate
pip list
pip uninstall tabulate

Then use the package:

from tabulate import tabulate
rows = [["Asha", 91], ["Ravi", 78]]
print(tabulate(rows, headers=["Name", "Marks"]))

If pip is not found, try python -m pip install tabulate.

Common mistakes

  • Naming your own file random.py or math.py: Python imports your file instead of the real module.
  • Typing pip install inside the Python shell: it is a terminal command.
  • ModuleNotFoundError: the package is not installed, or it was installed for a different Python.
  • Forgetting the module name: after import math, write math.sqrt(), not sqrt().

Key points

  • import module, from module import name, and import module as alias are the three import styles.
  • math, random and datetime come with Python; nothing to install.
  • Any .py file can be imported as a module from the same folder.
  • pip install name adds third-party packages.

Practice questions

1. Write code that rolls two dice and prints their total.
import random
a, b = random.randint(1, 6), random.randint(1, 6)
print(a, b, "total", a + b)
2. What is the difference between math.ceil(2.1) and round(2.1)?

math.ceil(2.1) is 3 (always rounds up); round(2.1) is 2 (nearest whole number).

3. How many days old are you? Write the code.
from datetime import date
born = date(2010, 5, 14)
print((date.today() - born).days)
4. You named your file random.py and random.randint now fails. Why?

import random finds your file first, and your file has no randint. Rename your file.

5. Where do you type pip install requests?

In a terminal such as Command Prompt or the VS Code terminal, not in the Python shell.