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