Python modules and packages allow you to organize code into reusable components, making it easier to manage large projects.
__init__.py file.A module is just a .py file that contains Python code (functions, variables, classes, etc.).
1. Create a file math_operations.py with the following code:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b2. Now, import and use the module in another Python file:
import math_operations
result = math_operations.add(5, 3)
print("Addition:", result)The math_operations module is imported and used.
Instead of importing the entire module, you can import specific functions.
from math_operations import add
print("Sum:", add(4, 6))Only the add function is imported.
You can rename modules using as.
import math_operations as mo
print("Subtraction:", mo.subtract(10, 4))Python includes many built-in modules.
import math
import random
print(math.sqrt(16)) # 4.0
print(random.randint(1, 10)) # Random number between 1 and 10The math and random modules provide ready-to-use functions.
A package is a directory containing multiple modules, along with an __init__.py file.
my_package/
│── __init__.py
│── module1.py
│── module2.py1. Create module1.py inside my_package:
def greet(name):
return f"Hello, {name}!"2. Import and Use the Package:
from my_package import module1
print(module1.greet("Ankit"))The function from module1.py is used.
You can install third-party packages using pip.
pip install numpyimport numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)numpy is installed and used.
A module is a Python file containing code.
A package is a collection of modules inside a directory with an __init__.py file.
Use import to bring modules into your program.
Use pip to install third-party packages.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.