As your programs grow larger, you don't want to keep all your code in a single file. Modules and Packages allow you to organize your code into different files and folders, making it easier to manage, debug, and share.
1. What is a Module?
A module is simply a file containing Python code (with a .py extension). You can "import" the functions or variables from one file into another.
Standard Modules: Python comes with built-in modules like
math,random, andos.Custom Modules: Any
.pyfile you create can be imported as a module.
2. What is a Package?
A package is a directory (folder) that contains multiple modules. It must typically contain a file named __init__.py to be recognized as a package.
3. Code Example: Topic 13
Step 1: Create a file named calculator.py (The Module)
def add(a, b):
return a + b
def multiply(a, b):
return a * bStep 2: Use the module in your main.py
# Option 1: Import the whole module
import calculator
print(calculator.add(5, 3))
# Option 2: Import specific functions
from calculator import multiply
print(multiply(10, 2))
# Option 3: Use built-in modules
import math
print(math.sqrt(64)) # Output: 8.04. External Packages (pip)
Python has a massive ecosystem of 3rd-party packages (like pandas for data or requests for web). You install them using a tool called pip via your terminal:
pip install requests