Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Custom Module in Python

Python Modules

Python Modules – Complete Guide With Examples

A module in Python is a file that contains functions, classes, and variables which can be reused in other Python programs. Modules help in organizing code logically, making programs cleaner, structured, and easier to maintain.

Why Do We Use Modules?

  • To reuse code across multiple files
  • To keep programs clean and structured
  • To group related functions into separate files
  • To avoid rewriting the same logic again and again
  • To make debugging easier

How a Module is Created?

In Python, a module is automatically created using the file name. If you create a Python file named a.py, then Python treats a as a module.

# a.py
def fun1():
    print("fun1")

def fun2():
    print("fun2")

How to Import a Module in Another File?

To access the functions inside a.py from b.py, we use the import keyword.

# b.py
import a      # importing module a.py

a.fun1()
a.fun2()

Explanation:

  • import a loads the file a.py as module a
  • a.fun1() calls the function fun1 inside module a

Different Ways to Import Modules

1. Simple Import

import math
print(math.sqrt(25))

2. Import With Alias

Alias makes module name shorter.

import math as m
print(m.sqrt(36))

3. Import Specific Function

from math import sqrt
print(sqrt(49))

4. Import All Functions (Not Recommended)

from math import *
print(factorial(5))

Types of Python Modules

1. Built-in Modules

These come with Python installation:

  • math – mathematical functions
  • datetime – date & time
  • random – random numbers
  • os – operating system operations
  • sys – system-level operations

2. User-Defined Modules

Created by the programmer (like a.py).

3. Third-Party Modules

Installed using pip:

pip install numpy
pip install pandas
pip install flask

Module Search Path in Python

When you import a module, Python searches for it in the following order:

  1. Current directory
  2. Python installed libraries
  3. External site-packages
import sys
print(sys.path)

Using __name__ == "__main__" in Modules

This is one of the most important concepts in modules. It is used to differentiate between:

  • When a file is executed directly
  • When a file is imported as a module
# a.py
def fun():
    print("Function Called")

if __name__ == "__main__":
    print("Running as main file")
    fun()
# b.py
import a     # this will NOT execute the main block of a.py

Why is this useful?

  • Prevents unwanted execution when importing
  • Makes module reusable
  • Helps in testing code

Creating a Module With Multiple Categories of Functions

# calculator.py
def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def multi(a, b):
    return a * b

def div(a, b):
    return a / b
Usage:
# main.py
import calculator as c

print(c.add(10, 20))
print(c.multi(5, 6))

Advanced Topic: Packages (Folder Modules)

What is a package?

A package is a folder containing multiple module files.

mypackage/
    __init__.py
    student.py
    teacher.py
    fees.py
Importing from packages:
from mypackage.student import getStudentData
from mypackage.teacher import getTeacherData

Benefits of Using Modules & Packages

  • Enhances maintainability
  • Improves code modularity
  • Allows team-based development
  • Reduces file sizes
  • Improves debugging and testing

Practical Example – User Module for Student Record

# student.py
def getStudent(rno, name, branch):
    print("Roll No:", rno)
    print("Name:", name)
    print("Branch:", branch)
# main.py
import student

student.getStudent(1001, "Manish", "CS")

Assignment – Practice Module Programs

  1. Create a Calculator module and import it into multiple files.
  2. Create a Student Management module with functions:
    • addStudent()
    • deleteStudent()
    • updateStudent()
  3. Create a package bank containing:
    • account.py
    • loan.py
    • customer.py
  4. Create a module for employee salary calculation.
  5. Create a login authentication module and call it from another file.

Post a Comment

0 Comments