Python Modules
Definition of a Module
A module in Python is a file containing Python code (functions, classes, or
variables) that can be reused in other Python programs using the import
statement.
A file named my_module.py is a module if it contains Python definitions.
Types of Modules
Type Description Example
Built-in Modules Pre-installed with Python math, random
User-defined Modules Custom modules created by the my_module.py
user
Third-party Modules External modules installed via pip numpy, pandas
1. Built-in Module Example: math
import math
print("Square root of 16 is:", [Link](16))
Output: Square root of 16 is: 4.0
2. User-defined Module Example
Step 1: Create fruit_module.py
# fruit_module.py
def is_fruit(name):
fruits = ['apple', 'banana', 'mango']
return [Link]() in fruits
Step 2: Use it in [Link]
# [Link]
import fruit_module
item = "Apple"
if fruit_module.is_fruit(item):
print(f"{item} is a fruit!")
else:
print(f"{item} is not a fruit.")
Output: Apple is a fruit!
3. Third-party Module Example: numpy
Install it using:
pip install numpy
Then use it:
import numpy as np
arr = [Link]([1, 2, 3])
print("Numpy Array:", arr)
Summary Table
Feature Module Type Example
Pre-installed Built-in math, datetime
Created by user User-defined fruit_module
Installed via Third-party numpy, pandas
pip
How to Create a Python Module
🧑💻 Step 1: Create a .py file (This is your module)
File name: fruit_module.py
Code:
python
CopyEdit
# fruit_module.py
def is_fruit(item):
fruits = ['apple', 'banana', 'mango']
return [Link]() in fruits
def fruit_message(item):
if is_fruit(item):
return f"{[Link]()} is a fruit."
else:
return f"{[Link]()} is not a fruit."
✅ This file is now your module.
🚀 Step 2: Use the module in another Python file
File name: [Link]
# [Link]
import fruit_module # Import your module
item = input("Enter an item: ")
message = fruit_module.fruit_message(item)
print(message)
When you run [Link], it will use the functions defined in fruit_module.py.
Output Example:
Enter an item: Apple
Apple is a fruit.
You can also import specific functions:
from fruit_module import is_fruit
print(is_fruit("banana")) # Output: True
Module File Structure
project_folder/
├── fruit_module.py <-- Your module
└── [Link] <-- Your main program
📌 Notes:
Module name = filename (without .py)
Store module and main file in the same folder or set PYTHONPATH
You can reuse your module in any project by just importing it
from Keyword in Python (Used for Modules)
The from keyword in Python is used to import specific parts (functions, classes,
variables) from a module instead of importing the whole module.
Syntax
from module_name import item_name
You can also import multiple items:
from module_name import item1, item2
Or import everything using * (not recommended in large programs):
from module_name import *
Benefits of from Import
Advantage Explanation
Cleaner Code No need to write module_name.function()
Selective Import Only import what you need
Better Readability Focuses on used functions or classes
⚠️Caution
Avoid from module import * in large projects because:
It pollutes the namespace
May cause name conflicts
Reduces code clarity
Difference between import and from ... import
Feature import module_name from module_name import item
What is Whole module Specific function, class, or
imported variable
Usage in code module_name.function_name() function_name() directly
Code May be longer Shorter, cleaner code
readability
Performance Slightly more overhead (loads More efficient if only 1–2 items
everything) needed
🔹 1. Using import
import math
print([Link](25)) # Using module name before function
2. Using from ... import
from math import sqrt
print(sqrt(25)) # No need to write 'math.'
When to Use Which?
Use Case Preferred Option
Need many functions from a module import module_name
Need only a few functions from module_name import f1
Want to avoid namespace conflicts import module_name
Want clean, short function calls from module import function
Avoid This (in large projects):
from math import *
print(sqrt(25))
Why not? It imports everything, which can lead to conflicts and makes code
hard to debug.
Summary
import math from math import sqrt
[Link](16) sqrt(16)
More namespace safety Less typing
Better for large modules Better for quick scripts