In programming, a module is a file that contains Python code. These files can be imported and used in other Python scripts to organize code and share functionality. Understanding how to create and use modules is an essential part of mastering Python.

What is a Module?

A module is a Python file that has a .py extension. It can contain functions, classes, and variables that can be imported into other Python scripts. Modules help in breaking down a large program into smaller, manageable pieces, which makes it easier to maintain and reuse code.

Creating a Module

To create a module, simply write your Python code in a file and save it with a .py extension. For example, let's create a module named calculator.py:

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

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

In this example, calculator.py contains two functions, add and subtract.

Importing Modules

To use the functions from the calculator.py module in another script, you need to import it. Here's how you can do it:

import calculator

result = calculator.add(5, 3)
print(result)  # Output: 8

You can also import only specific functions from a module:

from calculator import add

result = add(5, 3)
print(result)  # Output: 8

Best Practices

  • Use meaningful names for your modules and functions.
  • Keep your modules focused on a single task or purpose.
  • Follow the PEP 8 style guide for Python code formatting.

Further Reading

For more information on modules and their usage, check out the Python documentation on modules.

Python Module Diagram