Python Notes
Python ki features kya hain? Complete guide to Python
Introduction
What makes Python special among hundreds of programming languages? The answer lies in its carefully crafted set of features — design decisions made over three decades that collectively create a language that is simultaneously beginner-friendly and professional-grade. Python's features aren't accidents; each one was deliberately chosen to make code more readable, maintainable, and productive.
In this guide, we'll explore every major feature of Python — from its surface-level syntax design to its deeper runtime characteristics. We'll see each feature in action with code examples, understand *why* it exists, and appreciate how they work together to create the Python experience.
Hindi: Python ki features (visheshataen) use baaki languages se alag banati hain. Python ka syntax simple hai, isko seekhna aasaan hai, aur iska use har jagah hota hai. In features ki wajah se Python duniya ki most popular language bani hai.
Feature 1: Simple and Readable Syntax
Python's most celebrated feature is its readable, minimal syntax. The language was designed to look like pseudocode — the informal way programmers sketch out algorithms before writing real code.
Indentation as Structure
Python uses whitespace indentation to define code blocks instead of curly braces {}. This is controversial among some developers, but it forces consistent, readable formatting.
45°C → Dangerous Heat: Stay indoors 35°C → Hot Day: Stay hydrated 25°C → Comfortable: Enjoy the weather 10°C → Cold: Wear warm clothes
Hindi: Python mein curly braces {} ki jagah indentation (spaces/tabs) use hoti hai. Iska faida ye hai ki code automatically neat aur padha jaane wala hota hai. Agar aap indentation galat karein toh Python error deta hai — ye aapko clean code likhne ke liye majboor karta hai.Minimal Boilerplate
Python requires almost no "setup code." Compare reading a file:
# Python — clean and simple
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Java equivalent would require:
# try { BufferedReader reader = new BufferedReader(
# new FileReader("data.txt")); String line;
# StringBuilder sb = new StringBuilder();
# while ((line = reader.readLine()) != null) { ... }
# } catch (IOException e) { e.printStackTrace(); }
# — Python is about 4x fewer lines for the same task!
print("File reading complete!")File reading complete!
Feature 2: Dynamically Typed
Python is dynamically typed: variable types are determined at runtime, not compile time. You don't declare types when creating variables.
<class 'float'> HELLO [1, 1, 3, 4, 5] ['b', 'a', 'c']
Python 3.5+ Type Hints (Best of Both Worlds)
Python 3.5 added optional type hints — you can annotate types for tooling and documentation without losing dynamic flexibility:
BMI: 22.9 Hello, Rahul, Priya, Amit!
Feature 3: Object-Oriented Programming (OOP)
Python is a full-featured OOP language with classes, inheritance, encapsulation, and polymorphism:
Bruno (Labrador) says: Woof woof! 🐶 Whiskers says: Purrr... Meow! 🐱 Bruno fetches the ball! 🎾 Animal(name='Bruno')
Hindi: Python mein OOP (Object-Oriented Programming) use karna bahut easy hai. Class banao, objects banao, inheritance use karo — sab kuch clearly aur simply likha jaata hai.
Feature 4: Functional Programming Support
Python supports functional programming with first-class functions, lambdas, map/filter/reduce:
apply_twice(double, 3) = 12 Squares: [1, 4, 9, 16, 25] Evens: [2, 4] Ranking: 1. Priya: 95 2. Sita: 91 3. Rahul: 85 4. Amit: 72
List Comprehensions — Python's Functional Crown Jewel
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Even squares: [4, 16, 36, 64, 100]
Multiplication table (4x4):
[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
[4, 8, 12, 16]
Word lengths: {'Python': 6, 'Java': 4, 'C++': 3, 'Go': 2}
Unique remainders mod 5: [0, 1, 2, 3, 4]Feature 5: Generators and Iterators
Python's generator feature allows lazy evaluation — computing values on demand rather than all at once, saving memory:
0 1 4 9 16 List of 10,000 squares: 85,176 bytes Generator for 10,000 squares: 104 bytes Memory saved: 85,072 bytes (819x more efficient!)
Generator Expressions
# Generator expression — like list comprehension but lazy
gen = (x**2 for x in range(1_000_000)) # No memory used yet!
# Get first 5 values
for i, val in enumerate(gen):
if i >= 5:
break
print(val, end=" ")
print("\n(Only computed what was needed)")0 1 4 9 16 (Only computed what was needed)
Hindi: Generators Python ki ek powerful feature hai jisme hum values ko ek ek karke generate karte hain, saari ek saath nahi. Isse memory bachti hai. Jaise ek tap se pani — poora samundar ek saath nahi, ek ek drop aata hai jab zaroorat ho.
Feature 6: Decorators
Decorators allow you to modify or enhance functions/classes without changing their code — a powerful tool for logging, caching, access control, and more:
import time
import functools
# Decorator that times how long a function takes
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"⏱️ {func.__name__}() took {end - start:.4f} seconds")
return result
return wrapper
# Decorator that logs function calls
def logger(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"📞 Calling: {func.__name__}({args}, {kwargs})")
result = func(*args, **kwargs)
print(f"✅ Returned: {result}")
return result
return wrapper
# Stack multiple decorators!
@timer
@logger
def calculate_sum(n: int) -> int:
"""Calculate sum of first n numbers"""
return sum(range(n + 1))
# Call the decorated function
total = calculate_sum(100)📞 Calling: calculate_sum((100,), {})
✅ Returned: 5050
⏱️ calculate_sum() took 0.0001 secondsFibonacci sequence: 💾 Cached result for (0,) fib(0) = 0 💾 Cached result for (1,) fib(1) = 1 💾 Cached result for (2,) fib(2) = 1 ⚡ Cache hit for (1,) 💾 Cached result for (3,) fib(3) = 2 ⚡ Cache hit for (2,) 💾 Cached result for (4,) fib(4) = 3 ...
Feature 7: Context Managers (with statement)
The with statement provides clean resource management — automatically handling setup and teardown:
# Without context manager — error-prone
file = open("data.txt", "w")
try:
file.write("Hello, World!")
finally:
file.close() # Must remember to close!
# With context manager — clean and safe
with open("data.txt", "w") as file:
file.write("Hello, World!")
# File automatically closed here, even if an error occurs!
# Custom context manager
from contextlib import contextmanager
import time
@contextmanager
def timer_context(operation_name: str):
"""Context manager that times an operation"""
print(f"▶️ Starting: {operation_name}")
start = time.time()
try:
yield # Code inside the 'with' block runs here
finally:
elapsed = time.time() - start
print(f"⏹️ Finished: {operation_name} in {elapsed:.3f}s")
# Usage
with timer_context("Data Processing"):
data = list(range(1_000_000))
total = sum(data)
print(f" Sum of 1M numbers: {total:,}")▶️ Starting: Data Processing Sum of 1M numbers: 499,999,500,000 ⏹️ Finished: Data Processing in 0.052s
Feature 8: Exception Handling
Python has comprehensive exception handling that makes error recovery clean and structured:
✅ Connected to db.example.com:5432 (Attempted: db.example.com:5432)
Hindi: Exception handling Python ka ek important feature hai jisse aap program ke errors ko gracefully handle kar sakte ho.trymein risky code dalte hain,exceptmein error hone pe kya karna hai ye batate hain.
Feature 9: Duck Typing
Python uses duck typing — if it walks like a duck and quacks like a duck, it's a duck. Python doesn't check *what type* an object is, it checks *what it can do*:
It says: Woof! It moves: Runs on 4 legs It says: BEEP BOOP It moves: Rolls on wheels It says: Hello! It moves: Walks on 2 legs
Feature 10: Comprehensive Standard Library
Python's "batteries included" standard library covers almost every common programming need:
JSON output:
{
"name": "Rahul",
"score": 95,
"subjects": [
"Python",
"SQL"
]
}
Current directory: /home/user/project
SHA-256 hash: 89e01536ac207279409...
Mean: 86.4
Median: 86.5
Std Dev: 7.18Feature 11: Multi-paradigm Programming
Python supports multiple programming paradigms — use the style that best fits your problem:
Procedural: 220 Functional: 220 Pythonic: 220 All equal? True
Feature 12: Interactive Mode (REPL)
Python's REPL (Read-Eval-Print Loop) allows you to test code interactively — essential for learning and debugging:
Feature 13: Cross-Platform Compatibility
Python runs on virtually every platform without modification:
Feature 14: Automatic Memory Management (Garbage Collection)
Python manages memory automatically — you don't manually allocate or free memory:
Creating objects... Created: Obj1 Created: Obj2 Deleting obj1 reference... Garbage collected: Obj1 Running garbage collector manually... Collected 0 objects Script ending — obj2 will be collected automatically Garbage collected: Obj2
Hindi: Python mein memory management automatic hoti hai. C/C++ mein aapko khud memory allocate aur free karni padti thi, lekin Python mein ye sab automatically hota hai. Python ka Garbage Collector un objects ko automatically delete karta hai jo ab use nahi ho rahe.
Feature 15: Dataclasses (Python 3.7+)
Python 3.7 introduced dataclasses — a way to create clean data-holding classes with minimal code:
Student(Rahul, Roll: 101, Grade: B) Average: 88.4 Marks: [85, 90, 88, 92, 87] Student(Priya, Roll: 102, Grade: A) Average: 96.0 Marks: [95, 98, 96, 97, 94]
Key Points / Summary
- Simple syntax: Indentation-based, English-like, minimal boilerplate — most readable language.
- Dynamic typing: Variables don't need type declarations; types are checked at runtime.
- Type hints (3.5+): Optional annotations for documentation and tooling support.
- Object-oriented: Full OOP with classes, inheritance, polymorphism, and special methods.
- Functional features: First-class functions, lambdas, map/filter, list comprehensions.
- Generators: Memory-efficient lazy evaluation with the
yieldkeyword. - Decorators: Modify functions/classes without changing their code — AOP in Python.
- Context managers: Clean resource management via
withstatement. - Duck typing: Behavior matters more than type — flexible and powerful.
- Standard library: "Batteries included" — hundreds of built-in modules.
- Multi-paradigm: Supports procedural, OOP, and functional styles.
- REPL: Interactive mode for quick testing and learning.
- Cross-platform: Runs on Windows, macOS, Linux, mobile, cloud, and embedded devices.
- Automatic memory management: Garbage collector handles memory — no manual
malloc/free. - Dataclasses: Concise, auto-generated class boilerplate (Python 3.7+).
Interview Questions
Q1. What does "dynamically typed" mean? How is it different from "strongly typed"?
Dynamically typed means types are checked at *runtime*, not compile time — you don't declare variable types. Strongly typed means Python *enforces* type correctness — you can't silently concatenate an int and a string (unlike JavaScript). Python is *both* — dynamically AND strongly typed.
Q2. What is duck typing in Python?
Duck typing means Python doesn't check the type of an object, it checks what methods/attributes it has. The name comes from: "If it walks like a duck and quacks like a duck, it is a duck." Python'sforloop works on any object that has__iter__— whether it's a list, tuple, dict, generator, or custom class.
Q3. What is the difference between a list comprehension and a generator expression?
A list comprehension[x2 for x in range(n)]evaluates all values immediately and stores them in memory. A generator expression(x2 for x in range(n)) is lazy — it computes values one-by-one when requested. For large datasets, generators are much more memory-efficient.
Q4. What are decorators? Give a real-world use case.
Decorators are functions that wrap other functions to add functionality without changing the original code. Real-world uses: (1)@login_requiredin Django — checks if user is logged in before executing a view, (2)@cache— memoizes expensive function results, (3)@property— converts a method into a read-only attribute, (4)@staticmethod/@classmethod— modifies method behavior in classes.
Q5. How does Python manage memory? What is the GIL?
Python uses reference counting as its primary memory management strategy — objects are freed when their reference count drops to zero. A cyclic garbage collector handles circular references. The GIL (Global Interpreter Lock) is a mutex that prevents multiple native threads from executing Python bytecode simultaneously in CPython — this limits true parallelism. Python 3.13 introduces an experimental no-GIL mode to address this.
Next Steps
You now know Python's powerful features. Continue your journey:
- 🚀 Python Applications — See how all these features are used in real-world applications
- 💻 Install Python and practice each feature in the REPL
Practice Exercise:
⚠️ Common Mistakes
Python ki features seekhte waqt beginners kuch common galtiyan karte hain. Inhe avoid karo! 🚫
❌ Mistake 1: Mixing Tabs and Spaces for Indentation
# ❌ WRONG — tabs aur spaces mix karna
def greet():
print("Hello") # tab use kiya
print("World") # spaces use kiya — IndentationError!
# ✅ CORRECT — hamesha 4 spaces use karo
def greet():
print("Hello")
print("World")Hindi: Python mein tabs aur spaces ko mix karna allowed nahi hai. Hamesha 4 spaces ka consistent indentation use karo. Apne editor mein "spaces on tab" setting ON rakho.
❌ Mistake 2: Thinking Dynamic Typing Means No Type Errors
# ❌ WRONG — dynamic typing ka matlab ye NAHI ki kuch bhi kar sakte ho
name = "Rahul"
age = 25
result = name + age # TypeError! str + int not allowed
# ✅ CORRECT — explicit conversion karo
result = name + str(age) # "Rahul25"
print(result)Rahul25
Hindi: Python dynamically typed hai par strongly typed bhi hai. Matlab aap variable ka type change kar sakte ho, lekin incompatible types ko mix nahi kar sakte without conversion.
❌ Mistake 3: Modifying a List While Iterating Over It
[1, 3, 5]
Hindi: Jab aap list ko iterate kar rahe ho tab usko modify mat karo — results unpredictable hote hain. List comprehension ya naya list banao.
❌ Mistake 4: Using Mutable Default Arguments
['a'] ['a', 'b'] ['a'] ['b']
Hindi: Python mein function ke default arguments sirf EK BAAR evaluate hote hain (jab function define hota hai). Mutable defaults (list, dict) ko avoid karo — None use karo instead.❌ Mistake 5: Confusing is with ==
True False x is None
Hindi:==values compare karta hai,ismemory location check karta hai (dono same object hain ya nahi).Nonecheck karne ke liye hameshais Noneuse karo,== Nonenahi.
❌ Mistake 6: Forgetting self in Class Methods
# ❌ WRONG — self bhool gaye
class Calculator:
def add(a, b): # self missing!
return a + b
# calc = Calculator()
# calc.add(2, 3) # TypeError: add() takes 2 args but 3 were given
# ✅ CORRECT — self always first parameter
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print(calc.add(2, 3))5
Hindi: Class ke instance methods mein self pehla parameter hona zaroori hai. Python automatically current object pass karta hai, isliye agar self miss karo toh argument count mismatch hoga.❌ Mistake 7: Not Using Context Managers for File Operations
# ❌ WRONG — file close karna bhool sakte ho
f = open("data.txt", "w")
f.write("Hello")
# Agar yahan error aaye toh file close nahi hogi!
f.close()
# ✅ CORRECT — with statement use karo (auto-close)
with open("data.txt", "w") as f:
f.write("Hello")
# File automatically closed — even if error occurs! ✅Hindi: with statement (context manager) use karo file operations ke liye. Ye automatically file close kar deta hai chahe error aaye ya na aaye. Memory leaks aur data loss se bachata hai.✅ Key Takeaways
Is chapter se aapko ye important points yaad rakhne chahiye: 📝
- 🐍 Python ka syntax English jaisa hai — beginners ke liye perfect starting language hai, aur professionals ke liye bhi powerful enough hai
- 📐 Indentation mandatory hai — ye sirf style nahi, ye Python ka grammar hai. Clean code likhna majboori hai, choice nahi
- 🔄 Dynamic typing = flexibility — variables ka type runtime pe decide hota hai, lekin Python strongly typed bhi hai (implicit conversion nahi hoti)
- 🏗️ Multi-paradigm support — OOP, Functional, Procedural — teeno styles ek hi language mein use kar sakte ho. Project ke according choose karo
- ⚡ Generators memory bachate hain — large datasets ke saath kaam karte waqt
yielduse karo, poora data memory mein load mat karo - 🎭 Decorators = superpower — bina function ka code change kiye uski functionality enhance kar sakte ho (logging, caching, auth)
- 🦆 Duck typing = behavior matters — Python mein object ka type nahi, uska behavior check hota hai. "If it quacks like a duck..."
- 📚 Standard Library = batteries included — 200+ built-in modules hain, har cheez ke liye third-party package install karne ki zaroorat nahi
- 🌍 Cross-platform portability — ek baar likho, kahin bhi chalao (Windows, Mac, Linux, Cloud, Raspberry Pi)
- 🧹 Garbage Collection automatic hai — memory management ki tension nahi, Python khud handle karta hai reference counting + cyclic GC se
❓ FAQ
Q1: Python slow hai toh industry mein itna popular kyun hai? 🤔
Answer: Haan, Python raw execution speed mein C/C++ se slow hai. Lekin popularity ke reasons hain: (1) Developer productivity — Python mein 10 lines ka code Java mein 50 lines lagta hai, (2) Critical parts C mein likhe hain — NumPy, Pandas internally C use karte hain, (3) Time is money — fast development > fast execution for most applications, (4) AI/ML ecosystem — TensorFlow, PyTorch sabse pehle Python support karte hain.
Q2: Kya Python mein real private variables hain? 🔒
Answer: Nahi, Python mein TRUE private variables nahi hain (unlike Java/C++). _variable convention hai (protected), __variable name mangling karta hai (pseudo-private), lekin technically access ho sakta hai. Python ki philosophy hai: "We are all consenting adults here" — trust developers to follow conventions.
Q3: Type hints daalein toh Python slow ho jaata hai kya? ⚡
Answer: Bilkul nahi! Type hints sirf documentation aur tooling ke liye hain. Python runtime pe type hints ko completely IGNORE karta hai — koi performance impact nahi hota. Ye sirf editors (VS Code, PyCharm) aur type checkers (mypy, pyright) ke liye useful hain.
Q4: Generator aur Iterator mein kya difference hai? 🔄
Answer: Iterator ek protocol hai — koi bhi object jo __iter__() aur __next__() implement kare wo iterator hai. Generator iterator banane ka easy tarika hai — yield keyword use karke. Har generator ek iterator hai, lekin har iterator generator nahi hota. Generator functions automatically iterator protocol implement karti hain.
Q5: Python 2 aur Python 3 mein kya major differences hain? 🆚
Answer: Python 2 officially dead hai (2020 se EOL). Major differences: (1) print function vs statement, (2) Integer division: 3/2 = 1 (Py2) vs 1.5 (Py3), (3) Unicode by default in Py3, (4) range() returns iterator in Py3, (5) Type hints only in Py3. Always use Python 3.10+ for new projects.
Q6: Kya Python mein multi-threading properly kaam karti hai? 🧵
Answer: GIL (Global Interpreter Lock) ki wajah se CPU-bound tasks mein multi-threading effective nahi hai — ek time pe sirf ek thread Python bytecode execute karta hai. Solutions: (1) multiprocessing module use karo CPU-bound ke liye, (2) asyncio use karo I/O-bound ke liye, (3) Python 3.13+ mein experimental free-threading (no-GIL) mode available hai.
Q7: List comprehension aur map()/filter() mein kaunsa better hai? 📋
Answer: List comprehension zyada Pythonic aur readable hai — community mein preferred hai. map()/filter() functional programming style hai. Performance almost same hai. Rule of thumb: Agar logic simple hai toh list comprehension use karo, agar already ek function defined hai toh map() use kar sakte ho.
Q8: Python seekhne ke baad kaunsi field mein jaayein? 🎯
Answer: Python se multiple career paths open hote hain: (1) Web Development — Django, FastAPI, Flask, (2) Data Science/ML — Pandas, Scikit-learn, TensorFlow, (3) Automation/DevOps — scripting, Ansible, AWS Lambda, (4) Backend Engineering — APIs, microservices, (5) Cybersecurity — penetration testing tools. Apni interest ke according choose karo!
🎯 Interview Questions (Extended)
Pehle ke 5 questions ke alawa, ye additional important interview questions hain:
Q6. What are Python's key differences from Java and C++?
Python is interpreted (no compilation step), dynamically typed (no type declarations), uses indentation for blocks (no curly braces), has automatic memory management (no manual malloc/free), and supports multiple paradigms natively. Python trades raw speed for developer productivity — 3-5x fewer lines of code for equivalent programs.
Q7. Explain the difference between deepcopy and shallow copy in Python.
Shallow copy (copy.copy()orlist.copy()) creates a new object but references the same nested objects. Deep copy (copy.deepcopy()) recursively copies all nested objects too. Example: if you shallow copy a list of lists, modifying an inner list affects both copies. Deep copy creates completely independent objects.
Q8. What are context managers and how do you create a custom one?
Context managers handle setup/teardown viawithstatement. Create custom ones using: (1) A class with__enter__and__exit__methods, or (2)@contextlib.contextmanagerdecorator with a generator function containingyield. They ensure cleanup happens even if exceptions occur — used for files, database connections, locks, and temporary state changes.
Q9. What is the difference between @staticmethod and @classmethod?
@staticmethoddoesn't receive any implicit first argument — it's just a regular function that lives inside a class (no access toclsorself).@classmethodreceives the class itself as first argument (cls) — it can access/modify class state and is commonly used as an alternative constructor (factory method pattern).
Q10. How does Python's garbage collection work internally?
Python uses a two-pronged approach: (1) Reference counting — every object has a count of references pointing to it; when count reaches zero, memory is freed immediately. (2) Generational garbage collector — handles circular references that reference counting can't detect. Objects are grouped into 3 generations (0, 1, 2); newer objects are collected more frequently. You can control it via the gc module.Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Features - Complete Guide 2026.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, introduction, features, python features - complete guide 2026
Related Python Master Course Topics