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.
1# math_operations.py23def add(a, b):4 """Add two numbers and return the result."""5 return a + b67def subtract(a, b):8 """Subtract b from a and return the result."""9 return a - b1011# A constant12PI = 3.141591314def 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:
1# Import the entire module2import math_operations34# Now we can use functions from the module5result = math_operations.add(10, 5)6print(f"10 + 5 = {result}")78# We can also access constants9print(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 moreLearn how to use classes and objects in Python.
Learn moreLearn how to work with files in Python.
Learn more