Chapter 7: Python Modules & Packages – Organizing Your Code

Previous Chapter Table of Contents Next Chapter

1. What is a Module?

A module is a Python file (.py) containing reusable code (functions, variables, classes).

Key benefits:

  • Organize related code together
  • Promote code reuse
  • Prevent naming conflicts

my_module.py

# my_module.py
PI = 3.14159

def circle_area(radius):
    return PI * radius ** 2

def rectangle_area(length, width):
    return length * width

Exercise 1: Create a Module

Create a module named string_utils.py with:

  1. A function reverse_string(s)
  2. A function count_vowels(s)
  3. Test it in another file

2. Importing Modules

1. Import Entire Module

import math
print(math.sqrt(25))

2. Import Specific Items

from math import sqrt, pi
print(sqrt(9))  # No math prefix

3. Import with Alias

import numpy as np
arr = np.array([1, 2, 3])

Exercise 2: Random Password Generator

Using the random module:

  1. Create a function that generates 8-character passwords
  2. Include uppercase, lowercase, and digits
  3. Use random.choice()

3. Packages

Package Structure

Package directory structure

Package Structure Example:

my_package/
├── __init__.py
├── module1.py
└── subpackage/
    ├── __init__.py
    └── module2.py

Importing from packages:

from my_package import module1
from my_package.subpackage import module2

Exercise 3: Create a Package

Create a package named shapes with:

  1. Module circle.py with area/circumference functions
  2. Module rectangle.py with area/perimeter functions
  3. Import and test the package

4. Python Standard Library

Module Purpose Example Use
os Operating system interactions os.listdir()
datetime Date/time handling datetime.now()
json JSON data handling json.loads()
sys System-specific parameters sys.argv

Exercise 4: File Organizer

Using the os module:

  1. List all files in current directory
  2. Print only .txt files
  3. Print file sizes

Previous Chapter Contents Next Chapter