What is a Module in Python?
A module is a Python file containing reusable code such as variables, functions, classes, and statements. Modules help organize large programs into smaller and maintainable files.
Any Python file with a .py extension can be used as a module and imported into another Python program.
Module
A Python file containing reusable functions, classes, variables, or logic.
import
Used to bring a module into another Python program.
from ... import
Used to import specific functions, classes, or variables from a module.
Reusable Code
Modules allow the same code to be reused across multiple programs.
Create a Python file named calculator.py. This file becomes a module.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
The functions inside calculator.py can now be reused by another Python file.
Use the import statement to import a module.
import calculator
result = calculator.add(10, 20)
print("Result:", result)
Result: 30
The module name is followed by a dot and the function name.
In a real application, calculation logic can be separated into its own module.
def calculate_total(price, quantity):
return price * quantity
def calculate_discount(amount, discount):
return amount - (amount * discount / 100)
import calculator
amount = calculator.calculate_total(1000, 3)
final_amount = calculator.calculate_discount(
amount,
10
)
print("Total:", amount)
print("After discount:", final_amount)
Total: 3000
After discount: 2700.0
Instead of importing the entire module, you can import only the required function.
from calculator import add
result = add(50, 25)
print("Result:", result)
Result: 75
Now the function can be called directly using add().
Multiple functions can be imported from the same module.
from calculator import add, subtract, multiply
print(add(10, 5))
print(subtract(10, 5))
print(multiply(10, 5))
15
5
50
Python also allows importing all names from a module using the * symbol.
from calculator import *
print(add(10, 20))
print(subtract(20, 10))
The as keyword can give a module a shorter or more convenient name.
import calculator as calc
result = calc.add(100, 200)
print("Result:", result)
Result: 300
Banking applications can separate account-related operations into a reusable module.
def deposit(balance, amount):
return balance + amount
def withdraw(balance, amount):
if amount > balance:
return balance, "Insufficient balance"
return balance - amount, "Withdrawal successful"
import bank
balance = 10000
balance = bank.deposit(balance, 5000)
balance, message = bank.withdraw(
balance,
3000
)
print(message)
print("Balance:", balance)
Withdrawal successful
Balance: 12000
A module can contain variables that can be reused by other Python programs.
company_name = "ABC Technologies"
company_location = "Pune"
employee_count = 250
import company
print("Company:", company.company_name)
print("Location:", company.company_location)
print("Employees:", company.employee_count)
Company: ABC Technologies
Location: Pune
Employees: 250
Employee-related functions can be placed in a separate module and reused throughout an HR application.
def calculate_annual_salary(monthly_salary):
return monthly_salary * 12
def calculate_bonus(monthly_salary):
return monthly_salary * 0.10
def employee_summary(name, salary):
annual_salary = calculate_annual_salary(salary)
bonus = calculate_bonus(salary)
return name, annual_salary, bonus
import employee
name, salary, bonus = employee.employee_summary(
"Rahul",
50000
)
print("Employee:", name)
print("Annual Salary:", salary)
print("Bonus:", bonus)
Employee: Rahul
Annual Salary: 600000
Bonus: 5000.0
Python includes many ready-to-use modules in its standard library.
| Module | Common Use |
|---|---|
| math | Mathematical operations |
| random | Generate random values |
| datetime | Date and time operations |
| os | Operating system operations |
| json | JSON data processing |
| statistics | Statistical calculations |
The math module provides useful mathematical functions.
import math
amount = 10000
rate = 1.08
result = amount * math.sqrt(4)
print("Square root:", math.sqrt(144))
print("Rounded value:", math.ceil(12.3))
Square root: 12.0
Rounded value: 13
The random module can be used for OTPs, random selections, games, and test data.
import random
otp = random.randint(100000, 999999)
print("Your OTP is:", otp)
Your OTP is: 583214
The datetime module is commonly used for invoices, employee attendance, order dates, and reports.
from datetime import datetime
order_date = datetime.now()
print("Order Date:", order_date)
print("Year:", order_date.year)
print("Month:", order_date.month)
print("Day:", order_date.day)
Order Date: 2026-09-21 10:30:15
Year: 2026
Month: 9
Day: 21
The json module is commonly used when applications exchange data with APIs and web services.
import json
customer = {
"name": "Rahul",
"age": 28,
"city": "Pune"
}
json_data = json.dumps(customer)
print(json_data)
{"name": "Rahul", "age": 28, "city": "Pune"}
The os module provides functions for interacting with files, folders, and the operating system.
import os
print("Current Folder:")
print(os.getcwd())
print("Files and Folders:")
print(os.listdir())
This is useful for automation, file-processing systems, backup applications, and server-side programs.
A module can contain classes as well as functions.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display(self):
print("Product:", self.name)
print("Price:", self.price)
from product import Product
item = Product("Laptop", 75000)
item.display()
Product: Laptop
Price: 75000
An e-commerce application can keep product-related logic in a separate reusable module.
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def is_available(self):
return self.stock > 0
def display(self):
print("Product:", self.name)
print("Price:", self.price)
print("Available:", self.is_available())
from product import Product
laptop = Product(
"Laptop",
65000,
10
)
laptop.display()
Product: Laptop
Price: 65000
Available: True
Python provides the special __name__ variable. It can be used to determine whether a file is being executed directly or imported as a module.
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(10, 20))
The code inside the if block runs when the file is executed directly, but not when it is imported.
Billing logic can be separated from the main application.
def calculate_subtotal(price, quantity):
return price * quantity
def calculate_tax(amount, tax_rate):
return amount * tax_rate / 100
def calculate_total(price, quantity, tax_rate):
subtotal = calculate_subtotal(
price,
quantity
)
tax = calculate_tax(
subtotal,
tax_rate
)
return subtotal + tax
import billing
total = billing.calculate_total(
1000,
3,
18
)
print("Final Bill:", total)
Final Bill: 3540.0
Python searches specific locations when importing a module. The sys.path list contains locations that Python checks.
import sys
for path in sys.path:
print(path)
This becomes important when working with large applications containing multiple directories and packages.
Aliases make frequently used module names shorter and easier to work with.
import datetime as dt
import math as m
today = dt.datetime.now()
print("Today:", today)
print("Square Root:", m.sqrt(100))
Today: current date and time
Square Root: 10.0
| Concept | Meaning | Example |
|---|---|---|
| Module | A Python file containing reusable code | calculator.py |
| Function | A reusable block of logic | calculate_total() |
| Class | A blueprint for creating objects | Product |
- Give modules meaningful names.
- Keep related functions and classes together.
- Avoid putting unrelated logic into one module.
- Use clear and consistent naming conventions.
- Use from module import name when only a few names are required.
- Avoid unnecessary from module import *.
- Use __name__ == "__main__" for executable test code.
- Keep modules small and focused when possible.
- Add documentation for reusable modules.
- Use modules to reduce duplicate code.
A real employee-management application can split its responsibilities across multiple modules.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display(self):
print("Name:", self.name)
print("Salary:", self.salary)
def calculate_bonus(salary):
return salary * 0.10
def calculate_annual_salary(salary):
return salary * 12
from employee import Employee
import salary
employee = Employee(
"Priya",
60000
)
employee.display()
bonus = salary.calculate_bonus(
employee.salary
)
annual_salary = salary.calculate_annual_salary(
employee.salary
)
print("Bonus:", bonus)
print("Annual Salary:", annual_salary)
Name: Priya
Salary: 60000
Bonus: 6000.0
Annual Salary: 720000
| Rule | Explanation |
|---|---|
| .py file | A Python file can be used as a module. |
| import | Imports a complete module. |
| from ... import | Imports specific names from a module. |
| as | Creates an alias for a module or imported name. |
| __name__ | Identifies whether a module is run directly or imported. |
| Standard library | Python provides many ready-to-use modules. |
| Custom module | Developers can create modules for their own applications. |