Quest 2 • Lesson 2
📦 Modules & Packages
Learn how to organise your code with modules and packages – essential for building real‑world Python projects.
A module is a single Python file (`.py`) containing functions, classes, and variables. A package is a collection of modules organised in folders. They help you structure code logically and reuse it across projects.
🔧 Built-in Modules
Python comes with a wide range of built‑in modules. Let's explore a few.
Simulate importing and using built‑in modules:
📘 Example: using the math module
import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.14159 print(math.floor(3.7)) # 3
🛠️ Creating Your Own Module
Create a simple module with helper functions.
Simulate a module file:
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
def multiply(a, b):
return a * b
📁 Package Structure
A package is a folder with an `__init__.py` file (can be empty).
📁 utils/
📄 __init__.py
📄 strings.py
📄 numbers.py
📁 data/
📄 __init__.py
📄 database.py
📄 main.py
from utils.strings import capitalize
from utils.numbers import add
result = add(5, 3)
print(capitalize("hello")) # "Hello"
import math
import random
from datetime import datetime
# Creating a custom module (my_utils.py)
# Then import and use it
import my_utils
print(my_utils.greet("Alice"))
print(my_utils.add(5, 3))
# Importing from a package
from my_package.utils import helper
✨ Challenge: Build a Simple Package
Create a package structure with:
- A package called
math_ops. - Two modules:
basic.py(add, subtract) andadvanced.py(power, factorial). - Write a script that imports and uses both modules.
def add(a, b): return a + b
def subtract(a, b): return a - b
# math_ops/advanced.py
def power(a, b): return a ** b
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# main.py
from math_ops.basic import add, subtract
from math_ops.advanced import power, factorial
print(add(5, 3)) # 8
print(power(2, 4)) # 16
print(factorial(5)) # 120
➡️ Next Lesson
Lesson 2.3: Working with CSV & JSON – handle structured data.
Continue to Lesson 2.3 →(Coming soon – check back or buy Pro Pack for early access)
❤️ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
☕ Buy Me a Coffee