Modules & Packages
Code ko organized rakho � har feature apne file mein, Python ka standard library 200+ modules deti hai jo already built hain.
Modules kyun zaroori hain?
Jaise ek kitchen mein sab kuch alag alag jagah hota hai � masale alag, bartan alag, sabziyan alag � waise hi Python mein code bhi organized hona chahiye. Module ek Python file hai jo functions, variables aur classes ko ek jagah rakhta hai.
- Organization � har feature apne file mein hota hai
- Reusability � ek baar likha, hazaar jagah use karo
- Namespace � naming conflicts nahi hoti
- Standard Library � Python mein 200+ built-in modules hain jo already ready hain
import math � module load hota hai, use dot notation se access karo.
from math import sqrt � sirf specific function chahiye to from-import karo.
Third-party packages install karte hain � pip install requests jaisa.
Import: module load karo
Sabse basic tarika � import keyword se poora module load hota hai. Phir dot notation se kuch bhi access karo.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(math.ceil(4.3)) # 5Jab import math likhte ho to poora math module load hota hai. Uske andar jo bhi functions hain � sqrt, pi, ceil � sab math. ke baad likh kar access karte ho.
sqrt function bhi hai, to math.sqrt aur tumhara sqrt alag alag rahenge � koi conflict nahi.From Import: sirf zaroorat ka lo
Kabhi kabhi poora module load karne ki zaroorat nahi hoti. Sirf ek do functions chahiye to from ... import use karo.
from random import randint, choice
print(randint(1, 10)) # random number 1-10
print(choice(["a", "b", "c"])) # random item from list
# Ab randint directly use kar sakte ho � math. jaisa prefix nahi chahiyeIsme sirf randint aur choice import hain. Baaki random ke functions available nahi hain. Prefix bhi nahi lagana � seedha randint(1, 10) likh sakte ho.
# Import with alias (short name)
import datetime as dt
now = dt.datetime.now()
print(now.strftime("%d/%m/%Y")) # 01/09/2026
# from import bhi alias le sakta hai
from math import sqrt as square_root
print(square_root(25)) # 5.0Alias se lamba naam chhota kar sakte ho. datetime ko dt bana diya, sqrt ko square_root. Code padhne mein easy ho jata hai.
from math import * se sab kuch import hota hai � namespace pollution hota hai. Hamesha specific functions import karo.Python ke built-in modules
Python ka standard library bahut rich hai. Kuch most-used modules dekhte hain:
# datetime � dates aur times ke liye
import datetime
now = datetime.datetime.now()
print(now.strftime("%d/%m/%Y %H:%M"))
# Output: 01/09/2026 14:30
# os � operating system interactions
import os
print(os.getcwd()) # current directory
print(os.listdir(".")) # files in current dir
# sys � system parameters
import sys
print(sys.version) # Python version
print(sys.platform) # 'win32', 'linux', etc.
# json � JSON data handle karna
import json
data = {"name": "Aman", "age": 22}
json_str = json.dumps(data)
print(json_str) # {"name": "Aman", "age": 22}
parsed = json.loads(json_str)
print(parsed["name"]) # Aman
# collections � advanced containers
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
print(Counter(words))
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})Har module ka ek specific kaam hai. datetime dates ke liye, os system ke liye, json data interchange ke liye. Jab tak module import nahi karoge, tab tak available nahi hoga.
PIP: third-party packages
Python ka standard library bahut powerful hai, lekin kabhi kabhi chahiye � jaise web scraping ke liye requests, data analysis ke liye pandas. Inhe install karte hain pip se.
# Package install karo
pip install requests
# Multiple packages ek saath
pip install numpy pandas matplotlib
# Installed packages list karo
pip list
# Package info dekho
pip show requests
# Requirements file se install
pip install -r requirements.txtpip Python Package Installer hai. Ye PyPI (Python Package Index) se packages download karta hai jo 400,000+ packages ka repository hai. Terminal ya command prompt mein ye commands chalao.
python -m venv myenv se environment banao, myenv\Scripts\activate se activate karo. (Next lesson mein detail mein dekhenge.)Modules in action: practical examples
# Random password generator
import random
import string
def generate_password(length=12):
chars = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password(16))
# Output: aB3$kL9!mN2@pQ5#
# File size checker
import os
def file_size(filepath):
size = os.path.getsize(filepath)
if size < 1024:
return f"{size} B"
elif size < 1024**2:
return f"{size/1024:.1f} KB"
else:
return f"{size/1024**2:.1f} MB"
# Timer using time module
import time
start = time.time()
total = sum(range(1_000_000))
end = time.time()
print(f"Sum: {total}")
print(f"Time: {end - start:.4f} seconds")Dekho � random se passwords, os se file operations, time se performance measurement. Modules ke bina ye sab khud se likhna padta.
Concept grid: quick recap
import math � poora module load, dot notation se access.
from math import sqrt � sirf specific function, prefix nahi chahiye.
pip install requests � third-party packages install karo, 400,000+ available.
import datetime as dt � lamba naam chhota karo, code readable banao.
Quick check
math module import karo aur pi ki value print karo.
import keyword se module load karo, phir math.pi print karo.
Common mistakes
from math import *wildcard use karna � namespace pollution hota hai, specific functions import karo.- Module name galat likhna �
import Mathnahi,import math(lowercase). - Import statement ko function ke andar rakhna � hamesha file ke top par rakho.
- Pip install nahi karna aur third-party module import karne ki koshish � pehle install karo, phir import karo.
Great. Ab datetime aur math modules dekho � dates, times aur mathematical functions ka full power use karo.