Some text some message..
Back 15 🧠 What are Modules in Python? 25 Jun, 2025

🧠 What are Modules in Python?

A module is a single Python file (.py) that contains definitions (functions, variables, classes) you can use in other programs.

You can:

  • Create your own modules

  • Import built-in or third-party modules

✅ Example:

import math
print(math.sqrt(16))  # Output: 4.0

📦 What are Packages in Python?

A package is a collection of modules organized in directories that include a special __init__.py file.

✅ Example:

from datetime import datetime
print(datetime.now())

🔹 Ways to Import

import math                    # Import whole module
from math import sqrt         # Import specific function
import math as m              # Import with alias

✅ Built-in Modules in Python (no installation needed)

Module Use Case
math Mathematical functions like sqrt, sin, etc.
random Generate random numbers
datetime Work with dates and time
os Interact with the operating system
sys Access system-specific parameters
re Work with Regular Expressions
json Handle JSON data
statistics Mean, median, mode, etc.
time Work with timestamps, delays
collections Specialized container datatypes (Counter, deque)
itertools Tools for iterators (combinations, permutations)
functools Functional programming tools (reduce, lru_cache)

✅ Commonly Used External Packages (install via pip)

Package Description
numpy Numerical computing
pandas Data manipulation & analysis
matplotlib Data visualization
seaborn Statistical data visualization
scikit-learn Machine learning tools
tensorflow / torch Deep learning frameworks
requests Send HTTP requests
flask Lightweight web framework
django High-level web framework
openpyxl Excel file manipulation
beautifulsoup4 Web scraping
pytest Testing framework

🛠️ Custom Module Example

Create mymodule.py:

def greet(name):
    return f"Hello, {name}!"

Use in another file:

import mymodule
print(mymodule.greet("Abhi"))

📂 Python Package Example (Folder Structure)

my_package/
│
├── __init__.py
├── module1.py
└── module2.py

Use it like:

from my_package import module1

📦 Package Installation via pip

pip install numpy