Lesson 11 • Intermediate
Modules and Packages
Organize your code, reuse functionality, and explore Python's powerful built-in libraries.
What You'll Learn in This Lesson
- ✓What modules are and how they keep code organized
- ✓All 4 ways to import: import x, from x import y, as alias, *
- ✓The math module: sqrt, ceil, floor, pow, pi
- ✓The random module: random numbers, choices, shuffle
- ✓The datetime module: dates, times, formatting
- ✓How to install external packages with pip
What Are Modules?
A module is simply a Python file (.py) that contains code you can reuse. Instead of writing everything in one file, you split your code into organized pieces.
| Term | What It Is | Example |
|---|---|---|
| Module | A single .py file | math.py, helpers.py |
| Package | A folder of modules | my_app/ folder |
| Library | Collection of packages | requests, numpy |
Why Use Modules?
| Benefit | Description |
|---|---|
| Reusability | Write once, use everywhere |
| Organization | Keep related code together |
| Maintainability | Easier to find and fix bugs |
| Collaboration | Teams can work on different files |
Importing Modules
Use the import keyword to use a module:
| Style | Syntax | Usage |
|---|---|---|
| Import whole module | import math | math.sqrt(16) |
| Import specific item | from math import sqrt | sqrt(16) |
| Import with alias | import math as m | m.sqrt(16) |
| Import multiple | from math import sqrt, pi | sqrt(16), pi |
Import Styles
Different ways to import modules
# Different ways to import
import math
print("Using import math:")
print(f" math.sqrt(25) = {math.sqrt(25)}")
print(f" math.pi = {math.pi:.4f}")
from math import sqrt, ceil
print("\nUsing from math import sqrt, ceil:")
print(f" sqrt(49) = {sqrt(49)}")
print(f" ceil(4.2) = {ceil(4.2)}")
import datetime as dt
print("\nUsing import datetime as dt:")
print(f" Today: {dt.date.today()}")from math import * imports everything and can cause naming conflicts. Always be specific about what you import.The math Module
Python's built-in math module provides mathematical functions:
| Function | What It Does | Example |
|---|---|---|
| math.sqrt(x) | Square root | sqrt(16) → 4.0 |
| math.ceil(x) | Round up | ceil(4.2) → 5 |
| math.floor(x) | Round down | floor(4.8) → 4 |
| math.pow(x, y) | x to the power of y | pow(2, 3) → 8.0 |
| math.pi | Pi constant | 3.14159... |
Math Module
Mathematical operations
import math
print("=== Math Module ===")
print(f"Square root of 64: {math.sqrt(64)}")
print(f"2 to the power of 10: {math.pow(2, 10)}")
print(f"Ceiling of 3.2: {math.ceil(3.2)}")
print(f"Floor of 3.8: {math.floor(3.8)}")
print(f"Pi: {math.pi:.6f}")
print(f"Factorial of 5: {math.factorial(5)}")The random Module
Generate random numbers for games, testing, or simulations:
| Function | What It Does |
|---|---|
| random.randint(a, b) | Random integer from a to b (inclusive) |
| random.random() | Random float between 0 and 1 |
| random.choice(list) | Pick one random item |
| random.shuffle(list) | Shuffle list in place |
| random.sample(list, n) | Pick n random items |
Random Module
Generate random values
import random
print("=== Random Module ===")
print(f"Random number 1-100: {random.randint(1, 100)}")
print(f"Random decimal: {random.random():.4f}")
colors = ["red", "blue", "green", "yellow"]
print(f"Random color: {random.choice(colors)}")
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled: {numbers}")
print(f"Pick 2 colors: {random.sample(colors, 2)}")The datetime Module
Work with dates and times:
Datetime Module
Work with dates and times
from datetime import datetime, date, timedelta
# Current date and time
now = datetime.now()
print("=== Datetime Module ===")
print(f"Now: {now}")
print(f"Date only: {date.today()}")
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
# Formatting dates
print(f"\nFormatted: {now.strftime('%B %d, %Y')}")
print(f"Time: {now.strftime('%H:%M:%S')}")
# Date math
tomorrow = date.today() + timedelta(days=1)
next_week = date.today() + timedelta(weeks=1)
print(f"\nTomorrow: {tomorrow}")
prin
...The os Module
Interact with your computer's operating system:
OS Module
System operations
import os
print("=== OS Module ===")
print(f"Current directory: {os.getcwd()}")
print(f"Operating system: {os.name}")
# Path operations (works on any OS)
path = os.path.join("folder", "subfolder", "file.txt")
print(f"\nJoined path: {path}")
print(f"File name: {os.path.basename(path)}")
print(f"Directory: {os.path.dirname(path)}")
# Check if path exists
print(f"\nCurrent dir exists: {os.path.exists('.')}")The json Module
JSON (JavaScript Object Notation) is a universal format for storing and exchanging data. It's used by almost every API.
| Function | What It Does |
|---|---|
| json.dumps(obj) | Convert Python → JSON string |
| json.loads(string) | Convert JSON string → Python |
| json.dump(obj, file) | Write Python to JSON file |
| json.load(file) | Read JSON file to Python |
JSON Module
Work with JSON data
import json
# Python dictionary
user = {
"name": "Alice",
"age": 25,
"is_student": True,
"skills": ["Python", "JavaScript"]
}
# Convert to JSON string
json_string = json.dumps(user, indent=2)
print("=== Python to JSON ===")
print(json_string)
# Convert back to Python
parsed = json.loads(json_string)
print(f"\n=== Back to Python ===")
print(f"Name: {parsed['name']}")
print(f"Skills: {parsed['skills']}")Creating Your Own Module
Any Python file can be a module. Just save your code and import it:
Step 1: Create helpers.py
# helpers.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + bStep 2: Import in another file
# main.py
import helpers
print(helpers.greet("World"))
print(helpers.add(5, 3))Custom Module
Create your own reusable code
# Simulating a custom module
# This would be in my_helpers.py:
def greet(name):
return f"Hello, {name}!"
def calculate_area(length, width):
return length * width
PI = 3.14159
# Using the "module":
print(greet("Python Learner"))
print(f"Area: {calculate_area(5, 3)}")
print(f"PI value: {PI}")Understanding Packages
A package is a folder containing multiple modules. It must have an __init__.py file (can be empty).
my_package/
__init__.py ← Makes it a package
greetings.py ← Module 1
math_utils.py ← Module 2
helpers.py ← Module 3Importing from packages:
from my_package import greetings from my_package.math_utils import calculate import my_package.helpers as h
Installing External Packages with pip
pip is Python's package manager. It downloads packages from PyPI (Python Package Index) — a library of over 400,000 packages!
| Command | What It Does |
|---|---|
| pip install requests | Install a package |
| pip uninstall requests | Remove a package |
| pip list | Show installed packages |
| pip freeze | List packages with versions |
Popular packages to try:
- • requests — make HTTP requests to APIs
- • flask — build web applications
- • pandas — data analysis
- • pygame — create games
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
| from math import * | Can overwrite your variables | from math import sqrt |
| Naming file same as module | math.py shadows built-in math | Use unique file names |
| Circular imports | A imports B, B imports A | Restructure your code |
| Forgetting __init__.py | Folder not recognized as package | Add empty __init__.py |
Practical Example: Password Generator
Use multiple modules to create a random password generator:
Password Generator
Combine random and string modules
import random
import string
def generate_password(length=12):
"""Generate a secure random password."""
# All possible characters
characters = string.ascii_letters + string.digits + "!@#$%"
# Generate password
password = ''.join(random.choice(characters) for _ in range(length))
return password
# Generate passwords of different lengths
print("=== Password Generator ===")
print(f"8 chars: {generate_password(8)}")
print(f"12 chars: {generate_password(12)}")
print(f"16
...Practical Example: Date Calculator
Calculate days between dates and future dates:
Date Calculator
Work with dates
from datetime import datetime, date, timedelta
def days_until(target_date):
"""Calculate days until a target date."""
today = date.today()
target = datetime.strptime(target_date, "%Y-%m-%d").date()
delta = target - today
return delta.days
def add_days(start_date, days):
"""Add days to a date."""
start = datetime.strptime(start_date, "%Y-%m-%d").date()
result = start + timedelta(days=days)
return result.strftime("%B %d, %Y")
# Examples
print("=== Date Calcul
...Practical Example: Data Analyzer
Use json and math to analyze data:
Data Analyzer
Analyze JSON data
import json
import math
# Sample data (could come from a file or API)
data_json = '''
{
"students": [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78},
{"name": "Diana", "score": 95}
]
}
'''
# Parse JSON
data = json.loads(data_json)
scores = [s["score"] for s in data["students"]]
# Calculate statistics
average = sum(scores) / len(scores)
highest = max(scores)
lowest = min(scores)
print("=== Student Score An
...Summary: Quick Reference
| Concept | Description | Example |
|---|---|---|
| import x | Import whole module | import math |
| from x import y | Import specific item | from math import sqrt |
| import x as y | Import with alias | import pandas as pd |
| pip install x | Install package | pip install requests |
Key Built-in Modules:
- • math — mathematical functions
- • random — random number generation
- • datetime — dates and times
- • os — operating system interaction
- • json — JSON data handling
- • string — string constants and utilities
What's Next?
You now know how to organize your code into reusable modules, use Python's powerful standard library, and install external packages. This is how professional developers work!
Next up: Lesson 12 – Object-Oriented Programming — Learn to create classes and objects to model real-world concepts in your code.
🏅 Intermediate Track Complete! You now code like a real developer!
Functions, Lists, Dictionaries, File Handling, Exceptions, Modules — you've completed all 11 beginner and intermediate lessons. You now have the full Python toolkit that powers real applications.
🚀 Up next: Object-Oriented Programming — learn to model real-world things as classes and objects, the way all major software is built.
Sign up for free to track which lessons you've completed and get learning reminders.