Python Module
Python Module:
A module in Python is simply a file containing Python code (with a .py extension). It can include variables, functions, classes, or runnable code.
Why do we use Modules?
1. Reusability — Write once, use multiple times.
2. Organization — Break large programs into smaller manageable pieces.
3. Maintainability — Easier to update parts of your program.
4. Namespace Separation — Avoids conflicts between function/variable names.
5. Built-in Functions — Access powerful functionality via built-in libraries (e.g., math, random).
Types of Modules:
1. Built-in Modules — Pre-installed in Python (e.g., math, random).
2. User-defined Modules — Created by the user (e.g., mymodule.py).
3. Third-party Modules — Installed using pip (e.g., numpy, pandas).
Predefined (Built-in) Modules
Python comes with many ready-to-use modules. Examples below:
Examples of Built-in Modules
math Module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
random Module
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
datetime Module
import datetime
now = datetime.datetime.now()
print(“Current date and time:”, now)
os Module
import os
print(“Current directory:”, os.getcwd())
User-defined Modules
Step 1: Create a module (file):
# mymodule.py
def greet(name):
return f”Hello, {name}!”
def add(a, b):
return a + b
Step 2: Import and use the module:
# main.py
import mymodule
print(mymodule.greet(“Krishna”)) # Hello, Krishna!
print(mymodule.add(5, 3)) # 8
Alternative import style:
from mymodule import greet, add
print(greet(“Moni”)) # Hello, Moni!
print(add(2, 4)) # 6
Example: Combining Everything
math_tools.py
PI = 3.14159
def area_circle(radius):
return PI * radius * radius
def perimeter_circle(radius):
return 2 * PI * radius
app.py
Get Krishna Chaitanya’s stories in your inbox
Join Medium for free to get updates from this writer.
import math_tools
print(math_tools.area_circle(5)) # 78.53975
print(math_tools.perimeter_circle(5)) # 31.4159
Best Practices
— Use descriptive names for your modules.
— Group related functions and classes together.
— Avoid naming conflicts with built-in modules.
— Use __name__ == “__main__” to run tests only when the file is run directly.
Python Module Interview Questions
- What is a module in Python? How is it different from a script?
→ Explain the concept of a.pyfile used for reuse vs. a script that is typically executed directly. - What are the advantages of using modules in Python?
→ Discuss reusability, organization, namespace separation, and modular programming. - Explain the difference between built-in, user-defined, and third-party modules.
→ Clarify their origin, usage, and how they are imported. - How do you create and use a user-defined module in Python?
→ Give a real-world example of defining functions in one.pyfile and using them in another. - What is the use of
__name__ == "__main__"in modules?
→ Explain how this helps run test code only when the file is executed directly. - How can you reload a module without restarting the Python interpreter?
→ Answer withimportlib.reload(module_name). - What is the difference between
import module,from module import name, andfrom module import *?
→ Highlight namespace management, readability, and risks of wildcard imports. - How can you access a module that is located in another directory?
→ Mentionsys.path.append('path')or use of packages and relative imports. - What are some common built-in modules in Python and their uses?
→ Example:math,datetime,os,random,json. - How do you install and use third-party modules in Python?
→ Show commandpip install <module>and how to import after installation.
Practice Tasks for Python Modules
Task 1: Create and Use a Simple Module
- Create a module
calc.pywith functionsadd,subtract,multiply, anddivide - Import it into another script and perform all operations.
Task 2: Build a Geometry Toolkit
- Create a file
geometry.pywith functions to calculate: - Area and perimeter of a circle
- Area and perimeter of a rectangle
- Use it in a separate file to display the results for given inputs.
Task 3: Use Built-in Modules
- Use the following modules:
math– to find square roots and factorials.random– to generate random passwords.datetime– to calculate age from date of birth.
Task 4: Directory Analyzer
- Use the
osmodule to: - List all files in a directory
- Count how many
.pyfiles are present - Create a new folder named
backup
Task 5: Reload Module During Development
- Create a module
temp.pywith a simple function. - Import and use it in another script.
- Change the function in
temp.py, then reload the module usingimportlib.








