Python Modules

Learn how to create, import, organize, and reuse Python modules with practical real-time examples from banking, e-commerce, employee management, billing, and application development.

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.

1. Creating a Simple Module

Create a Python file named calculator.py. This file becomes a module.

calculator.py
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.

2. Importing a Module

Use the import statement to import a module.

main.py
import calculator

result = calculator.add(10, 20)

print("Result:", result)
Output:
Result: 30

The module name is followed by a dot and the function name.

3. Real-Time Example: Calculator Module

In a real application, calculation logic can be separated into its own module.

calculator.py
→
import calculator
→
Use Functions
→
Result
calculator.py
def calculate_total(price, quantity):
    return price * quantity


def calculate_discount(amount, discount):
    return amount - (amount * discount / 100)
main.py
import calculator

amount = calculator.calculate_total(1000, 3)

final_amount = calculator.calculate_discount(
    amount,
    10
)

print("Total:", amount)
print("After discount:", final_amount)
Output:
Total: 3000
After discount: 2700.0
4. Importing Specific Functions

Instead of importing the entire module, you can import only the required function.

Python
from calculator import add

result = add(50, 25)

print("Result:", result)
Output:
Result: 75

Now the function can be called directly using add().

5. Importing Multiple Functions

Multiple functions can be imported from the same module.

Python
from calculator import add, subtract, multiply

print(add(10, 5))
print(subtract(10, 5))
print(multiply(10, 5))
Output:
15
5
50
6. Importing Everything from a Module

Python also allows importing all names from a module using the * symbol.

Python
from calculator import *

print(add(10, 20))
print(subtract(20, 10))
Best Practice: Avoid using from module import * in large applications because it can make it difficult to identify where names came from.
7. Giving a Module an Alias

The as keyword can give a module a shorter or more convenient name.

Python
import calculator as calc

result = calc.add(100, 200)

print("Result:", result)
Output:
Result: 300
8. Real-Time Example: Bank Module

Banking applications can separate account-related operations into a reusable module.

bank.py
def deposit(balance, amount):
    return balance + amount


def withdraw(balance, amount):

    if amount > balance:
        return balance, "Insufficient balance"

    return balance - amount, "Withdrawal successful"
main.py
import bank

balance = 10000

balance = bank.deposit(balance, 5000)

balance, message = bank.withdraw(
    balance,
    3000
)

print(message)
print("Balance:", balance)
Output:
Withdrawal successful
Balance: 12000
9. Module Variables

A module can contain variables that can be reused by other Python programs.

company.py
company_name = "ABC Technologies"
company_location = "Pune"
employee_count = 250
main.py
import company

print("Company:", company.company_name)
print("Location:", company.company_location)
print("Employees:", company.employee_count)
Output:
Company: ABC Technologies
Location: Pune
Employees: 250
10. Real-Time Example: Employee Module

Employee-related functions can be placed in a separate module and reused throughout an HR application.

employee.py
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
main.py
import employee

name, salary, bonus = employee.employee_summary(
    "Rahul",
    50000
)

print("Employee:", name)
print("Annual Salary:", salary)
print("Bonus:", bonus)
Output:
Employee: Rahul
Annual Salary: 600000
Bonus: 5000.0
11. Using Python Standard Library Modules

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
12. Real-Time Example: Math Module

The math module provides useful mathematical functions.

Python
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))
Output:
Square root: 12.0
Rounded value: 13
13. Real-Time Example: Random Module

The random module can be used for OTPs, random selections, games, and test data.

Python
import random

otp = random.randint(100000, 999999)

print("Your OTP is:", otp)
Example Output:
Your OTP is: 583214
Note: The generated OTP will normally be different each time the program runs.
14. Real-Time Example: Date and Time Module

The datetime module is commonly used for invoices, employee attendance, order dates, and reports.

Python
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)
Example Output:
Order Date: 2026-09-21 10:30:15
Year: 2026
Month: 9
Day: 21
15. Real-Time Example: JSON Module

The json module is commonly used when applications exchange data with APIs and web services.

Python
import json

customer = {
    "name": "Rahul",
    "age": 28,
    "city": "Pune"
}

json_data = json.dumps(customer)

print(json_data)
Output:
{"name": "Rahul", "age": 28, "city": "Pune"}
16. Real-Time Example: OS Module

The os module provides functions for interacting with files, folders, and the operating system.

Python
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.

17. Module with a Class

A module can contain classes as well as functions.

product.py
class Product:

    def __init__(self, name, price):
        self.name = name
        self.price = price

    def display(self):
        print("Product:", self.name)
        print("Price:", self.price)
main.py
from product import Product

item = Product("Laptop", 75000)

item.display()
Output:
Product: Laptop
Price: 75000
18. Real-Time Example: E-Commerce Product Module

An e-commerce application can keep product-related logic in a separate reusable module.

product.py
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())
main.py
from product import Product

laptop = Product(
    "Laptop",
    65000,
    10
)

laptop.display()
Output:
Product: Laptop
Price: 65000
Available: True
19. Using __name__ in a Module

Python provides the special __name__ variable. It can be used to determine whether a file is being executed directly or imported as a module.

calculator.py
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.

20. Real-Time Example: Billing Module

Billing logic can be separated from the main application.

billing.py
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
main.py
import billing

total = billing.calculate_total(
    1000,
    3,
    18
)

print("Final Bill:", total)
Output:
Final Bill: 3540.0
21. Module Search Path

Python searches specific locations when importing a module. The sys.path list contains locations that Python checks.

Python
import sys

for path in sys.path:
    print(path)

This becomes important when working with large applications containing multiple directories and packages.

22. Module Aliases in Real Projects

Aliases make frequently used module names shorter and easier to work with.

Python
import datetime as dt
import math as m

today = dt.datetime.now()

print("Today:", today)
print("Square Root:", m.sqrt(100))
Output:
Today: current date and time
Square Root: 10.0
23. Module vs Function vs Class
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
24. Module Best Practices
  • 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.
Remember: A well-designed module should have a clear purpose and provide reusable functionality to other parts of the application.
25. Complete Real-Time Example: Employee Management

A real employee-management application can split its responsibilities across multiple modules.

employee.py
class Employee:

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display(self):
        print("Name:", self.name)
        print("Salary:", self.salary)
salary.py
def calculate_bonus(salary):
    return salary * 0.10


def calculate_annual_salary(salary):
    return salary * 12
main.py
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)
Output:
Name: Priya
Salary: 60000
Bonus: 6000.0
Annual Salary: 720000
26. Important Python Module Rules
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.
Key Idea: Modules allow large Python applications to be divided into smaller, organized, reusable pieces of code.

Python Modules

Learn to organize and reuse Python code with real-time examples.