What Is a Module
What Is a Module
As programs grow, one file can become too large and hard to manage.
Python uses modules to organize code.
What Is a Module?
A module is a Python file that contains code.
It can contain:
- variables
- functions
- classes
Example:
math_tools.py
This file is a module.
Why Modules Matter
Modules help you:
- split code into files
- reuse code
- keep projects organized
- make code easier to read
Example Without Modules
Everything in one file:
def add(a, b):
return a + b
print(add(2, 3))
This works, but large projects become messy.
Example Module File
Create a file named:
math_tools.py
Add:
def add(a, b):
return a + b
Use the Module
Create another file:
main.py
Add:
import math_tools
print(math_tools.add(2, 3))
Output
5
Real Examples of Modules
mathrandomosjson
These are built-in modules.
One Project, Many Modules
Example project:
main.py
users.py
products.py
reports.py
Each file handles one job.
Code Along
Create:
greetings.py
Add function:
def hello():
print("Hello")
Import it in main.py.
Mini Challenge
Create a module named:
tools.py
Add function:
def double(number):
return number * 2
Use it in another file.
Expected output:
10
Real World Use Case
Large apps use many modules for users, payments, reports, files, and settings.
Quiz
- What is a module?
- What can a module contain?
- Why are modules useful?
- Is every
.pyfile a module?
Assignment
Create a module with one function that prints your name, then import it.
Summary
You learned that a module is a Python file used to organize and reuse code.