Modules and Packages

In this class, we will delve into modules and packages, which are tools that allow you to organize and reuse code in Python.

Modules Link to heading

  • A module is a Python (.py) file that contains code that can be imported and used in other programs.
  • Modules can be used to organize code into smaller, more manageable parts.
  • They can also be used to reuse code in different programs.

Example: Link to heading

# Creating a module called "functions.py"

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b


# Importing the "functions.py" module into another program

import functions

sum_result = functions.sum(1, 2)
subtraction_result = functions.subtract(2, 1)

print(sum_result)
print(subtraction_result)

Exit: Link to heading

3
1

In this example:

  • A module called “functions.py” is created that contains two functions: add and subtract.
  • The module “functions.py” is imported into another program.
  • The add and subtract functions are called from the imported module.

Packages Link to heading

  • A package is a collection or folder of related modules.
  • Packages can be used to organize code in a hierarchical structure.

Example: Link to heading

# Creating a package called "calculator"

# Module "calculator/sum.py"

def add(a, b):
    return a + b

# Module "calculator/subtraction.py"

def subtract(a, b):
    return a - b


# Importing the "calculator" package into another program

import calculator

sum_result = calculator.sum.add(1, 2)
subtraction_result = calculator.subtraction.subtract(2, 1)

print(sum_result)
print(subtraction_result)

Exit: Link to heading

3
1

In this example:

  • A package called “calculator” is created that contains two modules: “suma.py” and “resta.py”.
  • The “calculator” package is imported into another program.
  • The add and subtract functions are called from the imported package.

Exercise Link to heading

Create a module that contains functions to calculate the area and perimeter of a square.

<< Dictionaries >>