Modules in Python
Modules in Python help us organize code by storing related functions, variables, and classes in a separate file.
Instead of writing everything in one file, we can divide the program into modules and reuse them whenever needed.
What is a Module?
A module is a Python file that contains functions, variables, and classes, which can be imported and used in another Python program.
Why Modules Are Used
Modules are used to:
- Make code reusable
- Improve readability
- Organize large programs
Example
import math
print(math.sqrt(16))
Explanation
mathis a built-in Python module.import mathloads the module.sqrt(16)calculates the square root of 16.- The output is
4.0.
Types of Modules in Python
Python mainly has three types of modules:
- Built-in modules
- User-defined modules
- External (third-party) modules
1. Built-in Modules
Built-in modules are modules that come pre-installed with Python.
Example
import random
print(random.randint(1, 10))
Explanation
randomis a built-in module.randint(1, 10)generates a random number between 1 and 10.
2. User-Defined Modules
A user-defined module is created by the programmer.
Step 1: Create a Module (math_ops.py)
def add(a, b):
return a + b
Step 2: Use the Module
import math_ops
print(math_ops.add(5, 3))
Explanation
math_ops.pyis a module created by the user.- The
add()function is imported and used. - The result is
8.
3. External (Third-Party) Modules
External modules are modules developed by others and installed using
pip.
Example
import numpy as np
print(np.array([1, 2, 3]))
Explanation
numpyis an external module.- It is installed using
pip install numpy. - It is used for numerical operations.
Ways to Import Modules
1. import module_name
import math
print(math.pi)
2. from module import function
from math import sqrt
print(sqrt(25))
3. import module as alias
import math as m
print(m.factorial(5))