<aside> 💡 Exercise: Write a Python program to simulate a simple bank account with deposit, withdrawal, and balance operations.

</aside>

Part 1: Python Modules and Packages

In Python, a module is a file containing Python definitions and statements. It helps us to organize related code into a single file, which makes the code cleaner and easier to understand.

A Python package, on the other hand, is a directory of Python modules. It's a way of organizing related modules into a single directory hierarchy.

Python Modules

A Python module can be created by creating a .py file. For instance, you can create a math_operations.py file and include definitions and statements in it.

# math_operations.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

PI = 3.14159

You can then import this module into another Python script and use its functions and variables.


# main.py

import math_operations

print(math_operations.add(5, 3))  # prints 8
print(math_operations.subtract(5, 3))  # prints 2
print(math_operations.PI)  # prints 3.14159

Python also has several built-in modules that you can use. One example is the math module.


import math

print(math.pi)  # prints 3.141592653589793
print(math.sqrt(16))  # prints 4.0

You can import specific functions or variables from a module using the from ... import ... syntax.


from math_operations import add, subtract

print(add(5, 3))  # prints 8
print(subtract(5, 3))  # prints 2

Python Packages

A Python package is a way of organizing related modules into a single directory hierarchy. For instance, you can have a shapes package with separate modules for circle, square, and rectangle.


shapes/
    __init__.py
    circle.py
    square.py
    rectangle.py

The __init__.py file is required to make Python treat the directory as a package. This file can be left empty but we generally place the initialization code for that package in this file.

Here's an example of how you might structure the circle.py module:


# circle.py

from math import pi

def area(radius):
    return pi * radius ** 2

def circumference(radius):
    return 2 * pi * radius