Progress0%

9 of 20 topics completed

Python Modules and Packages

As your Python programs grow larger and more complex, organizing your code becomes essential. Python provides two key mechanisms for this: modules and packages. These allow you to break down your code into smaller, manageable, and reusable components.

Modules: The Building Blocks

A module in Python is simply a file containing Python code. It can define functions, classes, and variables that you can use in other Python programs.

Python
1# math_operations.py
2
3def add(a, b):
4 """Add two numbers and return the result."""
5 return a + b
6
7def subtract(a, b):
8 """Subtract b from a and return the result."""
9 return a - b
10
11# A constant
12PI = 3.14159
13
14def calculate_circle_area(radius):
15 """Calculate the area of a circle with the given radius."""
16 return PI * radius * radius

Using a Module

You can use a module in your program by importing it with the import statement:

Python
1# Import the entire module
2import math_operations
3
4# Now we can use functions from the module
5result = math_operations.add(10, 5)
6print(f"10 + 5 = {result}")
7
8# We can also access constants
9print(f"The value of PI is: {math_operations.PI}")

Python Packages

A package is a way of organizing related modules into a directory hierarchy. It's simply a directory that contains Python modules and a special __init__.py file.

Modules and packages are powerful tools for organizing Python code that help you build maintainable and reusable software.

Related Tutorials

Master creating and using functions in Python.

Learn more

Learn how to use classes and objects in Python.

Learn more

Learn how to work with files in Python.

Learn more