A module in Python is a single file (with a .py extension) that contains Python definitions and statements, such as functions, classes, and variables. Modules allow you to organize related code into separate files logically.
Creating and Importing a Module
To create a module, you simply write some Python code in a file with the .py extension. For example, let’s create a module named math_operations.py with a few functions:
# calculation.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing the Module
You can use import to bring the module into another file, making its functions available to use:
import calculation
result = calculation.add(5, 4)
print(result) # Output: 9
Importing Specific Functions or Variables
You can also import specific functions or variables from a module:
from calculation import add
result = add(10, 7)
print(result) # Output: 17
Using Aliases
You can use as to create an alias for a module or function:
import calculation as ca
result = ca.subtract(10, 5)
print(result) # Output: 5
Standard Library Modules
Python’s standard library provides a wide range of built-in modules, such as math, datetime, and random. You can import and use these without additional setup.
import math
print(math.sqrt(25)) # Output: 5.0
Python Module – Interview Questions
Q 1: What is a Python module?
Q 2: How do you use a module in Python?
Q 3: Can a module contain functions and classes?
Q 4: What is a built-in module?
Q 5: Can you create your own module?
Python Module – Objective Questions (MCQs)
Q1. What is a module in Python?
Q2. How do you import a module in Python?
Q3. Which statement imports only the sqrt function from the math module?
Q4. What is the output of the following code?
import math
print(math.pi)
Q5. Where does Python search for modules when you import one?