Lesson 9: Modules and Packages

How Python organizes code into reusable components

What Are Modules?

A module is simply a Python file that contains functions, variables, or classes. Modules help you organize code into logical units and reuse functionality across multiple programs.

Creating a Module

Create a file named mymath.py:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Importing a Module

import mymath

print(mymath.add(3, 5))

Importing Specific Functions

from mymath import add

print(add(10, 20))

Built‑in Python Modules

Python includes a large standard library. Some common modules:

import math
print(math.sqrt(16))   # 4.0

What Are Packages?

A package is a collection of modules organized in folders. A package must contain an __init__.py file (even if empty) to be recognized by Python.

Package Structure Example

mypackage/
    __init__.py
    math_tools.py
    string_tools.py

Importing from a Package

from mypackage.math_tools import add

Installing External Packages

You can install third‑party packages using pip:

pip install requests

Using an Installed Package

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

Why Modules and Packages Matter

Next Steps

Now that you understand modules and packages, you’re ready to learn how Python reads and writes files in Lesson 10: File Handling (read/write).

← Back to Lesson Index