How Python organizes code into reusable components
A module is simply a Python file that contains functions, variables, or classes. Modules help you organize code into logical units and reuse functionality across multiple programs.
Create a file named mymath.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
import mymath
print(mymath.add(3, 5))
from mymath import add
print(add(10, 20))
Python includes a large standard library. Some common modules:
math — mathematical functionsrandom — random numbersdatetime — dates and timesos — operating system utilitiesimport math
print(math.sqrt(16)) # 4.0
A package is a collection of modules organized in folders. A package must contain an __init__.py file (even if empty) to be recognized by Python.
mypackage/
__init__.py
math_tools.py
string_tools.py
from mypackage.math_tools import add
You can install third‑party packages using pip:
pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Now that you understand modules and packages, you’re ready to learn how Python reads and writes files in Lesson 10: File Handling (read/write).
← Back to Lesson Index