Python Notes
Comprehensive Python cheatsheet covering all important syntax, data structures, functions, OOP, libraries, and interview tips in one place with Hindi explanations.
Complete Python Reference Guide
Yeh cheatsheet Python ke saare important concepts ek jagah cover karta hai — interview se production code tak!
2. Operators
# Arithmetic
5 + 3 # 8
5 - 3 # 2
5 * 3 # 15
5 / 3 # 1.667 (float division)
5 // 3 # 1 (floor division)
5 % 3 # 2 (modulus)
5 ** 3 # 125 (power)
# Comparison
== != < > <= >=
# Logical
and or not
# Identity
x is y # Same object?
x is not y
# Membership
x in lst # Is x in lst?
x not in lst
# Bitwise
& | ^ ~ << >>
# Walrus (Python 3.8+)
if (n := len(lst)) > 3:
print(f"Long list: {n}")3. String Operations
4. List Operations
5. Dictionary Operations
6. Set Operations
7. Functions
8. OOP Cheatsheet
class Animal:
species = "Mammal" # Class variable
def __init__(self, name, sound):
self.name = name # Instance variable
self._sound = sound # Protected
self.__secret = "hidden" # Private (name mangling)
def speak(self): # Instance method
return f"{self.name}: {self._sound}"
@classmethod
def get_species(cls): # Class method
return cls.species
@staticmethod
def is_valid_name(name): # Static method
return isinstance(name, str) and len(name) > 0
@property
def info(self): # Property (getter)
return f"{self.name} ({self.species})"
def __str__(self): # String representation
return self.name
def __repr__(self): # Developer repr
return f"Animal('{self.name}', '{self._sound}')"
def __eq__(self, other): # Equality
return self.name == other.name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Woof") # Parent init
self.breed = breed
def speak(self): # Override
return f"{super().speak()}! (I'm a {self.breed})"
# Abstract classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
pass
# MRO
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__) # (D, B, C, A, object)9. Exception Handling
10. File I/O
11. Comprehensions Summary
12. Itertools & Functools
13. Concurrency Cheatsheet
14. Regex Cheatsheet
15. Common Built-in Functions
16. Python Best Practices — PEP 8 Quick Guide
# Naming conventions
variable_name = "snake_case" # Variables
CONSTANT_VALUE = 42 # Constants
ClassName = "PascalCase" # Classes
_private = "single underscore" # Private by convention
__name_mangling = "dunder" # Private with mangling
# Spacing
x = 1 + 2 # Spaces around operators
def func(a, b): # Spaces after commas
pass # 4-space indentation
# Line length: max 79 chars (PEP 8) or 120 (PEP 8 relaxed)
# Imports (order: stdlib > third-party > local)
import os
import sys
import requests
import numpy as np
from mymodule import MyClass
# String formatting: prefer f-strings
name = "Alice"
greeting = f"Hello, {name}!" # ✅
greeting = "Hello, " + name + "!" # ❌ (concatenation)
greeting = "Hello, {}!".format(name) # OK but verbose
# Comparisons
if x is None: # ✅ (not ==)
if x is True: # ✅ (not ==)
if not x: # ✅ (truthy check)
if len(lst) == 0: # ❌
if not lst: # ✅
# Docstrings
def function(arg):
"""
Brief description.
Args:
arg: Description of argument
Returns:
Description of return value
Raises:
ValueError: When...
"""
passQuick Interview Reference
Final Tip: Revision ke liye yeh cheatsheet print karo! Interviews mein concepts ke saath code examples dikhao. Practice makes perfect — LeetCode, HackerRank pe daily practice karo.
WoHoTech Python Master Course — Complete Syllabus
| Section | Topics |
|---|---|
| Advanced Python | Iterators, Generators, Decorators, Context Managers, Multithreading, Multiprocessing, Asyncio, Memory Management |
| Databases | SQLite3, MySQL, PostgreSQL, CRUD, SQLAlchemy ORM |
| Automation | Web Scraping, Selenium, Email, PDF, Task Scheduler |
| Interview Prep | Python Q&A, Coding Questions, OOP Q&A, Cheatsheet |
WoHoTech ke saath Python Master karo! 🚀
📤 Code Output Examples
Neeche kuch important code snippets ke outputs diye gaye hain jo interview mein commonly puchhe jaate hain:
# Data Types Output
x = 42
print(type(x))
print(isinstance(x, int))
print(isinstance(x, (int, float)))<class 'int'> True True
['h', 'e', 'l', 'l', 'o']
{1, 2, 3}
False False False False
True TrueLong list: 5
7 3 Hlo yhnWrd !dlroW nohtyP ,olleH
# f-string formatting
print(f"{3.14159:.2f}")
print(f"{1000000:,}")
print(f"{'center':^20}")3.14
1,000,000
center [0, 1, 4, 9, 16, 25] [0, 2, 4, 6, 8]
[('a', 3), ('b', 2)]# Set Operations
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
print(s1 | s2)
print(s1 & s2)
print(s1 - s2)
print(s1 ^ s2){1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}# Closures
def multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(5))
print(triple(5))10 15
# Generators
def gen():
yield 1
yield 2
yield 3
g = gen()
print(next(g))
print(next(g))
print(list(gen()))1 2 [1, 2, 3]
# MRO (Method Resolution Order)
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__)(<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)
120
Original: [[99, 2], [3, 4]] Shallow: [[99, 2], [3, 4]] Deep: [[1, 2], [3, 4]]
⚠️ Common Mistakes
Python beginners aur even experienced developers yeh mistakes commonly karte hain. Interview mein bhi yeh topics puchhe jaate hain! 🎯
1. Mutable Default Arguments ❌
2. == vs is Confusion ❌
# ❌ WRONG
if x == None: # Works but not Pythonic
pass
# ✅ CORRECT
if x is None: # Identity check for singletons
pass
# Note: Small integers (-5 to 256) are cached in CPython
a = 256; b = 256
print(a is b) # True (cached)
a = 257; b = 257
print(a is b) # False (not cached — different objects!)3. Modifying List During Iteration ❌
4. Variable Scope — UnboundLocalError ❌
# ❌ WRONG
count = 0
def increment():
count += 1 # UnboundLocalError! 😵
# ✅ CORRECT — global ya nonlocal use karo
count = 0
def increment():
global count
count += 15. Shallow Copy Trap ❌
6. String Immutability Confusion ❌
7. Late Binding in Closures ❌
✅ Key Takeaways
Yeh Python cheatsheet ke most important points hain jo aapko hamesha yaad rakhne chahiye: 💡
- 🐍 Mutable vs Immutable samajhna zaroori hai — list/dict/set mutable hain, str/tuple/int immutable. Interview mein yeh first question hota hai!
- 📝 f-strings use karo formatting ke liye — concatenation se avoid karo. Clean, fast, aur readable hai.
- 🔄 List comprehensions loops se zyada Pythonic aur fast hain — but readability sacrifice mat karo complex cases mein.
- 🧠 Generators use karo large data ke liye — memory efficient hain kyunki lazy evaluation karte hain.
- 🎭 Decorators samajhna must hai — Flask, Django, testing sab mein use hote hain.
@functools.wrapslagana mat bhoolna! - 📦 **
*argsaurkwargsflexible functions likhne ke liye essential hain — interview mein hamesha puchha jaata hai. - 🔒 Context managers (
withstatement) use karo file handling aur resource cleanup ke liye — manually close karna risky hai. - ⚡ Exception handling properly karo — bare
except:kabhi mat likho, specific exceptions catch karo. - 🧪
isvs==ka difference yaad rakho —isidentity check hai,==value comparison.Noneke liye hameshaisuse karo. - 🚀 PEP 8 follow karo — naming conventions, imports order, spacing. Production code mein yeh difference banata hai.
❓ FAQ
Q1: Python mein List aur Tuple mein kya difference hai? 🤔
Answer: List mutable hai (change kar sakte ho), Tuple immutable hai (change nahi hota). Tuple faster hai aur hashable bhi — isliye dictionary keys mein use ho sakta hai. Jab data change nahi hona chahiye, tuple use karo.
Q2: *args aur **kwargs kab use karte hain? 🎯
Answer: *args tab use karo jab aapko pata nahi kitne positional arguments aayenge (tuple ban jaata hai). **kwargs jab unknown keyword arguments accept karne ho (dict ban jaata hai). Dono saath mein bhi use ho sakte hain: def f(*args, **kwargs).
Q3: Python mein GIL kya hai aur CPU-bound tasks ke liye kya karna chahiye? ⚙️
Answer: GIL (Global Interpreter Lock) CPython mein ek lock hai jo ek time pe sirf ek thread ko execute hone deta hai. I/O-bound tasks ke liye threading/asyncio use karo, CPU-bound tasks ke liye multiprocessing use karo jo separate processes mein chalti hai.
Q4: Shallow copy aur Deep copy mein kya farak hai? 📋
Answer: Shallow copy sirf top-level copy karta hai — nested objects still shared rehte hain. Deep copy (copy.deepcopy()) puri nested structure ka independent copy banata hai. Nested lists/dicts ke liye hamesha deepcopy use karo.
Q5: Decorator kya hota hai aur kab use karte hain? 🎭
Answer: Decorator ek function hai jo doosre function ko modify karta hai bina uska code change kiye. @decorator syntax use hota hai. Use cases: logging, authentication, caching (@lru_cache), timing, access control. Flask mein @app.route bhi decorator hai!
Q6: Generator aur normal function mein kya difference hai? 🔄
Answer: Normal function return se ek value deta hai aur terminate ho jaata hai. Generator yield use karta hai — ek-ek value lazily produce karta hai aur state remember karta hai. Large datasets ke liye memory efficient — poora data memory mein load nahi hota.
Q7: Python mein with statement kya karta hai? 🔒
Answer: with statement context managers ke saath use hota hai. Yeh automatically resources cleanup karta hai (jaise file close karna) — chahe exception aaye ya na aaye. Internally __enter__() aur __exit__() methods call hote hain.
Q8: @staticmethod aur @classmethod mein kya difference hai? 🏗️
Answer: @staticmethod ko self ya cls nahi milta — utility function jaisa hai class ke andar. @classmethod ko cls milta hai (class reference) — factory methods aur alternative constructors banane ke liye use hota hai. @classmethod inheritance mein properly kaam karta hai.
🎯 Interview Questions
Quick-fire Python interview questions jo frequently puchhe jaate hain: 🔥
Q1: Python mein mutable aur immutable data types bataiye.
Answer: Mutable: list, dict, set, bytearray. Immutable: int, float, str, tuple, frozenset, bytes. Immutable objects ka hash fix hota hai, isliye dict keys mein use ho sakte hain.
Q2: == aur is mein kya difference hai?
Answer: == value comparison karta hai (content same hai?). is identity comparison karta hai (same object in memory?). None check ke liye hamesha is use karo: if x is None.
Q3: List comprehension aur generator expression mein kya difference hai?
Answer: List comprehension [x for x in range(10)] — poora list memory mein banata hai. Generator expression (x for x in range(10)) — lazily ek-ek value produce karta hai, memory efficient. Large data pe generator better hai.
Q4: Python mein self kya hai?
Answer: self current instance ka reference hai. Har instance method ka first parameter self hota hai. Isse instance variables access/modify karte hain. Python automatically pass karta hai — explicitly likhna padta hai definition mein.
Q5: deepcopy() kab zaroorat padti hai?
Answer: Jab nested objects (list of lists, dict of dicts) ko independently copy karna ho. shallow copy sirf outer object copy karta hai — inner objects shared rehte hain. copy.deepcopy() recursively sab copy karta hai.
Q6: Python mein decorator kaise kaam karta hai?
Answer: Decorator ek higher-order function hai. @decorator lagna matlab func = decorator(func). Original function ko wrap karta hai — extra functionality add karta hai (logging, timing, auth). @functools.wraps(func) lagao taaki original function metadata preserve ho.
Q7: try-except-else-finally ka execution order kya hai?
Answer: try → code execute hota hai. Agar exception aaye → except block. Agar NO exception → else block. finally → hamesha run hota hai (cleanup ke liye). Return statement bhi finally ke baad execute hota hai!
Q8: Python mein memory management kaise hota hai?
Answer: Python reference counting + garbage collector (cyclic references ke liye) use karta hai. Jab reference count 0 ho jaata hai, memory free hoti hai. gc module se garbage collection control kar sakte ho. Small integers (-5 to 256) aur interned strings cached rehte hain.
Q9: @staticmethod vs @classmethod vs regular method — kab kya use karna chahiye?
Answer: Regular method — instance-specific kaam ke liye (self milta hai). @classmethod — class-level operations, factory methods (cls milta hai, inheritance support). @staticmethod — utility function jo na instance na class pe depend kare (koi automatic parameter nahi milta).
Q10: Python mein multithreading ka limitation kya hai aur solution kya hai?
Answer: GIL (Global Interpreter Lock) — ek time pe sirf ek thread Python bytecode execute kar sakta hai. I/O-bound tasks ke liye threading kaam karti hai (GIL release hota hai I/O pe). CPU-bound ke liye multiprocessing module use karo — separate processes, separate GIL. Ya phir concurrent.futures.ProcessPoolExecutor use karo.
💡 Pro Tip: Interview mein sirf answer mat do — example code ke saath explain karo. Interviewer ko practical understanding dekhni hai, ratta nahi! Practice karo daily — WoHoTech ke saath Python Master karo! 🚀
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Master Cheatsheet.
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, interview, preparation, cheatsheet
Related Python Master Course Topics