In Python, modules are files that contain Python code such as functions, variables, and classes. Modules help you organize your code into separate files so it becomes clean, reusable, and easier to manage.
Instead of writing everything in one file, you can split your program into multiple modules.
🔹 What is a Module in Python?
A module is simply a Python file (.py) that contains reusable code.
👉 Example:
-
math_utils.py→ module -
main.py→ main program using module
🔹 Why Use Modules?
Modules are used to:
- Organize code
- Reuse functions
- Reduce repetition
- Improve readability
- Maintain large projects easily
🔹 Types of Modules in Python
Python has 3 main types of modules:
1. Built-in Modules
Already included in Python:
-
math -
random -
datetime -
os
2. User-defined Modules
Created by programmers
3. External Modules
Installed using pip:
-
numpy -
pandas -
requests
🔹 How to Import a Module
import module_name
🔹 Example: Using Built-in Module (math)
import math
print(math.sqrt(16))
🔸 Output:
4.0
🔹 Import Specific Function
from math import sqrt
print(sqrt(25))
🔸 Output:
5.0
🔹 Import with Alias
import math as m
print(m.factorial(5))
🔸 Output:
120
🔹 Creating Your Own Module
Step 1: Create a file my_module.py
def greet(name):
return "Hello " + name
def add(a, b):
return a + b
Step 2: Use the module in another file
import my_module
print(my_module.greet("Alex"))
print(my_module.add(10, 5))
🔸 Output:
Hello Alex
15
🔹 Import Specific Functions from Custom Module
from my_module import greet
print(greet("Sophy"))
🔹 Built-in Modules Example
🔹 1. Random Module
import random
print(random.randint(1, 10))
🔹 2. Datetime Module
import datetime
print(datetime.datetime.now())
🔹 3. OS Module
import os
print(os.getcwd())
🔹 Module vs Library vs Package
| Term | Meaning |
|---|---|
| Module | Single Python file |
| Package | Collection of modules |
| Library | Collection of packages |
🔹 Example Structure
project/
│── main.py
│── my_module.py
│── utils.py
🔹 Real-Life Example: Calculator Module
📌 Create calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
📌 Use it in main file
import calculator
print(calculator.add(5, 3))
print(calculator.multiply(4, 2))
🔸 Output:
8
8
🔹 Advantages of Using Modules
✔ Code reusability
✔ Better organization
✔ Easier debugging
✔ Faster development
✔ Clean project structure
🔹 Common Mistakes
❌ Wrong import:
import math.sqrt
✔ Correct:
from math import sqrt
🔹 Key Points to Remember
- Module = Python file
-
Use
importto use modules - Built-in modules come with Python
- You can create your own modules
- Helps manage large projects
🚀 Conclusion
Python modules are essential for writing professional and scalable programs. They help you break large code into small, reusable parts, making development faster and more organized.
Once you master modules, you are ready to build:
- Real applications
- Web apps
- Automation tools
- Large software systems


0 Comments