Control Flow — if/elif/else & Loops
Control Flow — if/elif/else & Loops 🔀
Programming ki backbone — Control Flow. Conditional statements se lekar loops tak, break/continue se lekar walrus operator aur match-case tak. 15 topics Basic se Advanced tak. Employee data ke real-world examples aur interview Q&A ke saath. Data Insights par.
📑 Is Chapter Mein Kya Sikhenge:
- 🟢 Basic: Introduction, if, if-else, if-elif-else
- 🟡 Medium: Nested if, Ternary Operator, Logical Operators
- 🟡 Medium: for Loop, while Loop
- 🔴 Advanced: break/continue/pass, Nested Loops, else with Loops
- 🔴 Advanced: Walrus Operator, match-case (Python 3.10+)
- 📋 Summary: Best Practices & Common Mistakes
📊 Sample Data — Employee Records (10 employees)
Is chapter ke saare examples Employee data par based honge. 10 employees across 4 departments with age, salary, experience.
| ID | Name | Age | Department | Salary | Experience |
|---|---|---|---|---|---|
| 101 | Aarav | 25 | IT | ₹50,000 | 2 yrs |
| 102 | Priya | 30 | HR | ₹75,000 | 7 yrs |
| 103 | Rahul | 28 | Finance | ₹60,000 | 5 yrs |
| 104 | Neha | 26 | IT | ₹55,000 | 3 yrs |
| 105 | Vikram | 35 | Marketing | ₹80,000 | 10 yrs |
| 106 | Anjali | 27 | IT | ₹58,000 | 4 yrs |
| 107 | Suresh | 40 | Finance | ₹90,000 | 15 yrs |
| 108 | Kavya | 24 | HR | ₹45,000 | 1 yr |
| 109 | Rohan | 32 | IT | ₹70,000 | 8 yrs |
| 110 | Meera | 29 | Marketing | ₹65,000 | 6 yrs |
1. Control Flow Introduction — Definition & Types 🟢
📘 Definition: Control Flow determines the ORDER in which statements are executed in a program. By default, Python executes code line-by-line (top to bottom). Control Flow statements allow you to change this default flow — make decisions (if/else), repeat code (loops), and jump around (break/continue). Python uses INDENTATION (4 spaces) to define code blocks — no curly braces like C/Java.
🎯 Samjho Hinglish Mein: Control Flow = "code kaise chalega decide karna". Bina control flow ke code sirf ek seedhi line mein chalega — koi decision nahi, koi repetition nahi. 3 main types: (1) Sequential — default, ek ke baad ek. (2) Conditional — if/else se decision. (3) Iterative — loops se repetition. Real-world example: HR system mein employee ka age check karke retirement decide karna (conditional), 100 employees ka data process karna (loop).
📋 Types of Control Flow:
| Type | Statements | Purpose |
|---|---|---|
| Sequential | Default execution | Top to bottom, line by line |
| Conditional | if, elif, else, match | Decision making |
| Iterative | for, while | Repetition |
| Jump | break, continue, pass, return | Alter loop/function flow |
💻 Indentation — Python's Backbone:
# Python uses INDENTATION (4 spaces) — NOT braces {}
age = 25
# Correct — 4 spaces indent
if age >= 18:
print("Adult") # inside if block
print("Can vote") # inside if block
print("End of program") # outside if block
# ❌ WRONG — inconsistent indentation!
# if age >= 18:
# print("Adult")
# print("Can vote") ← IndentationError!
# Rule: Same block = same indentation
# Best practice: use 4 spaces (PEP 8 standard)
# Tabs vs spaces — NEVER MIX! Use spaces only💬 Interview Q&A:
Q: Control flow kya hai aur kitne types ke hote hain?
Ans: Control flow programming mein statements ke execution order ko control karta hai. 4 types: (1) Sequential — default top-to-bottom. (2) Conditional — if/elif/else/match se decision-making. (3) Iterative — for/while se repetition. (4) Jump — break/continue/pass/return se flow alter. Without control flow, programs sirf static hote — dynamic logic control flow se hi aata hai. Real-world programming ka 80% control flow pe based hai.
Q: Python mein braces ki jagah indentation kyu use hoti hai?
Ans: Python ka design philosophy — "Readability counts". Braces se code messy dikhta hai, indentation naturally clean aur consistent formatting force karti hai. PEP 8 standard: 4 spaces per level. Fayde: (1) Code readable, (2) Consistent style, (3) Less typing. Drawback: IndentationError ho sakti hai galat spacing pe. Golden rule: pura file mein SAME indentation use karo — sirf spaces ya sirf tabs, mix mat karo!
2. if Statement — Simple Conditions 🟢
📘 Definition: The if statement executes a block of code ONLY when the given condition is True. Syntax: if condition: followed by indented code block. Condition can be any expression that evaluates to True/False (Boolean). If condition is False, the block is skipped entirely — no error, just skipped.
📋 Comparison Operators:
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | age == 25 |
| != | Not equal to | dept != "HR" |
| > | Greater than | salary > 50000 |
| < | Less than | age < 30 |
| >= | Greater or equal | exp >= 5 |
| <= | Less or equal | age <= 60 |
💻 Examples:
# Example 1: Basic if statement
salary = 50000
if salary > 40000:
print("Above minimum wage") # executes
age = 25
if age >= 18:
print("Eligible to work")
print("Can sign contract") # both execute (same block)
# If condition False — nothing happens (no error)
if age > 60:
print("Senior citizen") # skipped, age is 25
print("Program continues") # always executes# Example 2: Employee data validation
employee = {"name": "Aarav", "age": 25, "salary": 50000, "dept": "IT"}
# Check eligibility for bonus
if employee["salary"] >= 50000:
print(f"{employee['name']} eligible for annual bonus")
# Multiple conditions with logical operators
if employee["age"] < 30 and employee["dept"] == "IT":
print(f"{employee['name']} qualifies for tech training program")
# String membership check
if "Aar" in employee["name"]:
print("Name contains 'Aar'")
# Truthy check — non-empty string is True
if employee["name"]:
print("Employee name exists")# Example 3: Truthy & Falsy values
# These are FALSY in Python (evaluate to False in if):
# False, None, 0, 0.0, "" (empty string), [] (empty list),
# {} (empty dict), () (empty tuple), set() (empty set)
# Real-world: check if data exists
skills = []
if skills: # False — empty list
print("Employee has skills")
else:
print("No skills listed") # this runs
# Bonus amount check
bonus = 0
if bonus: # False — 0 is falsy!
print(f"Bonus: ₹{bonus}")
else:
print("No bonus this year")
# Employee data check
manager = None
if manager: # None is falsy
print(f"Manager: {manager}")
else:
print("No manager assigned") # runs
# Explicit check (better in some cases)
if bonus > 0: # explicit, no ambiguity
print(f"Bonus: ₹{bonus}")=vs==— assignment vs comparison!if age = 25is SyntaxError.- Colon (
:) after condition mandatory hai —if age > 18:← don't forget! - Indentation consistent rakho — mixing tabs and spaces se IndentationError.
💬 Interview Q&A:
Q: Python mein truthy aur falsy values kya hain?
Ans: Python mein har value ka Boolean context hota hai. Falsy values (if mein False evaluate): False, None, 0, 0.0, "", [], {}, (), set() — empty ya zero cheezein. Truthy values: sab kuch else — non-empty strings, non-zero numbers, non-empty collections. Isliye if name: check karta hai name empty hai ya nahi. Use case: quick existence check. But explicit check (if len(name) > 0:) sometimes clearer hai — depends on readability preference.
Q: = aur == mein kya difference hai?
Ans: = ASSIGNMENT operator hai — variable ko value assign karta hai (x = 5). == COMPARISON operator hai — do values ko compare karta hai, True/False return karta hai (x == 5). Common mistake: if x = 5: → SyntaxError. Python explicitly assignment ko conditions mein disallow karta hai (unlike C where if (x = 5) works but is bug-prone). Python 3.8+ mein walrus operator := allow karta hai controlled assignment in expressions.
3. if-else Statement — Two-Way Decisions 🟢
📘 Definition: if-else provides TWO alternative code paths — one for True, one for False. Only ONE block executes based on the condition. Syntax: if condition: block1 else: block2. The else block runs when the if condition is False.
💻 Examples:
# Example 1: Basic if-else
age = 25
if age >= 18:
print("Adult — can vote")
else:
print("Minor — cannot vote")
# Even or odd
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd") # runs
# Password validation
password = "admin123"
if len(password) >= 8:
print("Password accepted")
else:
print("Password too short (min 8 characters)")# Example 2: Employee bonus eligibility
employee = {"name": "Priya", "experience": 7, "salary": 75000}
# Bonus calculation
if employee["experience"] >= 5:
bonus = employee["salary"] * 0.15 # 15% for senior
print(f"{employee['name']} — Senior bonus: ₹{bonus:.0f}")
else:
bonus = employee["salary"] * 0.05 # 5% for junior
print(f"{employee['name']} — Junior bonus: ₹{bonus:.0f}")
# Retirement check
age = 40
if age >= 60:
print("Retirement eligible")
else:
years_left = 60 - age
print(f"Years until retirement: {years_left}") # 20 years
# Department-based work assignment
dept = "IT"
if dept == "IT":
print("Assign coding project")
else:
print("Assign general task")# Example 3: Salary hike calculation
employees = [
{"name": "Aarav", "performance": 85, "salary": 50000},
{"name": "Priya", "performance": 92, "salary": 75000},
{"name": "Rahul", "performance": 65, "salary": 60000}
]
# Process each employee
for emp in employees:
if emp["performance"] >= 80:
hike = 0.20 # 20% for high performers
status = "Excellent"
else:
hike = 0.05 # 5% for others
status = "Average"
new_salary = emp["salary"] * (1 + hike)
print(f"{emp['name']}: {status} — New salary: ₹{new_salary:.0f}")
# Output:
# Aarav: Excellent — New salary: ₹60000
# Priya: Excellent — New salary: ₹90000
# Rahul: Average — New salary: ₹63000💬 Interview Q&A:
Q: if-else statement kya karta hai?
Ans: if-else two-way decision provide karta hai — condition True hai toh if block execute hoga, False hai toh else block. Sirf ek block hi run hoga, dono nahi. Syntax: if condition: ... else: .... Both blocks mandatory indented hote hain. else optional hai — sirf if bhi likh sakte ho. Real-world: pass/fail, approve/reject, weekday/weekend jaise binary decisions ke liye perfect.
Q: Kya else alone use kar sakte ho if ke bina?
Ans: Nahi! else hamesha if ke saath hi aata hai — standalone else SyntaxError deta hai. else means "if condition False hai toh" — bina condition ke else ka koi matlab nahi. But if alone use kar sakte ho (without else) — yeh valid hai. Similarly elif bhi if ke baad hi aata hai. Rule: else/elif always follow an if.
4. if-elif-else — Multiple Conditions 🟢
📘 Definition: elif (else-if) is used for MULTIPLE mutually exclusive conditions. Python checks each condition top-to-bottom, and executes the FIRST matching block. Once a match found, all other elif/else blocks are SKIPPED. Only ONE block runs, no matter how many elif branches. Ends with optional else block for "none of the above" case.
🎯 Samjho Hinglish Mein: if-elif-else = multiple choice question. Pehle if check, nahi mila toh next elif, nahi mila toh next elif, aur last mein else "default". Once koi condition match ho jaaye, baaki sab skip ho jaate hain. Real-world: grade calculation (A/B/C/D/F), salary bracket, age category, department-wise rules. Multiple simple ifs vs elif — elif efficient hai kyunki match hote hi ruk jaata hai.
💻 Examples:
# Example 1: Grade calculation
marks = 85
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A" # this runs (85 >= 80)
elif marks >= 70:
grade = "B" # skipped (already matched)
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
print(f"Marks: {marks} | Grade: {grade}") # Grade: A
# Note: Order matters! elif checks top-to-bottom
# If >= 60 was first, everyone would get "C"!# Example 2: Employee salary bracket classification
employees = [
{"name": "Aarav", "salary": 50000},
{"name": "Priya", "salary": 75000},
{"name": "Vikram", "salary": 80000},
{"name": "Kavya", "salary": 45000},
{"name": "Suresh", "salary": 90000}
]
for emp in employees:
sal = emp["salary"]
if sal >= 80000:
bracket = "Senior (30% tax)"
elif sal >= 60000:
bracket = "Mid (20% tax)"
elif sal >= 40000:
bracket = "Junior (10% tax)"
else:
bracket = "Trainee (no tax)"
print(f"{emp['name']} (₹{sal}): {bracket}")
# Output:
# Aarav (₹50000): Junior (10% tax)
# Priya (₹75000): Mid (20% tax)
# Vikram (₹80000): Senior (30% tax)
# Kavya (₹45000): Junior (10% tax)
# Suresh (₹90000): Senior (30% tax)# Example 3: Department-based work allocation
employees = [
{"name": "Aarav", "dept": "IT", "experience": 2},
{"name": "Priya", "dept": "HR", "experience": 7},
{"name": "Rahul", "dept": "Finance", "experience": 5},
{"name": "Vikram", "dept": "Marketing", "experience": 10}
]
for emp in employees:
dept = emp["dept"]
exp = emp["experience"]
if dept == "IT":
task = "Assigned coding project"
elif dept == "HR":
if exp >= 5:
task = "Senior HR — recruitment lead"
else:
task = "Junior HR — onboarding"
elif dept == "Finance":
task = "Quarterly report preparation"
elif dept == "Marketing":
task = "Campaign strategy planning"
else:
task = "General duties"
print(f"{emp['name']} ({dept}): {task}")- Order matters! Most specific conditions FIRST — otherwise wrong branch match hoga.
- Multiple ifs vs elif: Multiple
ifstatements sab check karte hain (independent).elifchain match hote hi ruk jaati hai (efficient). elseoptional hai — remove kar sakte ho if no default case needed.
💬 Interview Q&A:
Q: Multiple if statements aur if-elif-else chain mein kya difference hai?
Ans: Multiple ifs: Har condition INDEPENDENTLY check hoti hai — sab True ho sakte hain, sab execute hote hain. elif chain: Sequential check — first match hote hi RUK jaata hai, baaki skip. Example: if x>0: if x>10: — dono check honge. if x>0: elif x>10: — sirf first match. Performance: elif faster (short-circuit). Use case: mutually exclusive conditions → elif. Independent checks → multiple if. Bug source: elif ki jagah if likhna se overlapping matches hote hain.
Q: elif chain mein order kyu matter karta hai?
Ans: elif top-to-bottom check hoti hai — FIRST TRUE condition ka block execute hota hai, baaki skip. Agar overlapping conditions hain, order galat = wrong result. Example: grade calculation mein agar elif marks >= 50 pehle likh diya toh 90 marks wale ko bhi "D" milega (50+ true hai). Rule: most specific/highest condition FIRST, general/lowest LAST. Salary brackets: highest bracket first. Age groups: senior citizens first. Always test with edge cases (boundary values) to catch order bugs.
5. Nested if — Decision Trees 🟡
📘 Definition: A Nested if is an if statement INSIDE another if statement. Used when a decision depends on a previous decision — creating a hierarchical decision tree. Each nested level requires additional indentation (4 more spaces). Deep nesting (3+ levels) usually indicates code that should be refactored using logical operators or functions.
💻 Examples:
# Example 1: Basic nested if
age = 25
has_license = True
if age >= 18: # outer if
print("Adult")
if has_license: # nested if
print("Can drive legally")
else:
print("Need to get license")
else:
print("Minor — cannot drive")
# Loan eligibility check
age = 30
income = 75000
credit_score = 750
if age >= 21:
if income >= 50000:
if credit_score >= 700:
print("Loan approved ✅")
else:
print("Credit score too low")
else:
print("Income insufficient")
else:
print("Age below 21")# Example 2: Employee promotion eligibility
employees = [
{"name": "Aarav", "experience": 2, "performance": 85, "dept": "IT"},
{"name": "Priya", "experience": 7, "performance": 92, "dept": "HR"},
{"name": "Rahul", "experience": 5, "performance": 70, "dept": "Finance"}
]
for emp in employees:
if emp["experience"] >= 5:
if emp["performance"] >= 85:
if emp["dept"] in ["IT", "HR"]:
promotion = "Senior Manager"
else:
promotion = "Team Lead"
else:
promotion = "Consider next year"
else:
promotion = "Not eligible (need 5+ years)"
print(f"{emp['name']}: {promotion}")
# Output:
# Aarav: Not eligible (need 5+ years)
# Priya: Senior Manager
# Rahul: Consider next year# Example 3: Refactor deep nesting → cleaner code
# ❌ Deep nesting — hard to read (3 levels)
def check_bonus_bad(emp):
if emp["active"]:
if emp["experience"] >= 3:
if emp["performance"] >= 80:
return "Bonus approved"
else:
return "Low performance"
else:
return "Need more experience"
else:
return "Not active"
# ✅ Refactored — early return pattern (cleaner)
def check_bonus_good(emp):
if not emp["active"]:
return "Not active"
if emp["experience"] < 3:
return "Need more experience"
if emp["performance"] < 80:
return "Low performance"
return "Bonus approved"
# ✅ Or use logical operators (single condition)
def check_bonus_best(emp):
if emp["active"] and emp["experience"] >= 3 and emp["performance"] >= 80:
return "Bonus approved"
return "Not eligible"• Max 2-3 levels: Deep nesting hard to read — refactor into functions
• Early return: Fail fast, return early — avoids deep nesting
• Logical operators:
and/or se conditions combine karo instead of nesting• Guard clauses: Invalid cases pehle handle karo, main logic bad mein
💬 Interview Q&A:
Q: Nested if kab use karna chahiye aur kab avoid karna chahiye?
Ans: Use karo jab conditions dependent hain — outer condition True hone pe hi inner check karna hai (loan approval — pehle age check, phir income). Avoid karo jab: (1) 3+ levels deep ho jaaye — refactor. (2) Independent conditions hain — logical operators use karo. (3) Same pattern repeat ho — function banao. Deep nesting readability kill kar deta hai, testing mushkil, bugs increase. Solutions: early return, guard clauses, logical operators, or extract to functions. Rule of thumb: 2 levels max.
Q: Early return pattern kya hai?
Ans: Early return = invalid/exceptional cases ko pehle handle karke IMMEDIATELY return kar dena — main logic ko nested nahi karna. Instead of if valid: ... else: return error, likho if not valid: return error; .... Fayde: (1) Nesting kam, (2) Main logic top-level pe, (3) Read karna easy, (4) Debug asaan. Also called "guard clauses". Golden rule: happy path (main flow) should be top-level, error cases should return early. Popular in modern codebases (Go, Rust follow this heavily).
6. Ternary Operator — One-line if-else 🟡
📘 Definition: Ternary Operator is a concise ONE-LINE if-else that returns a value based on a condition. Syntax: value_if_true if condition else value_if_false. Useful for simple assignments and inline decisions. Python doesn't have C-style ?: — it uses this readable English-like syntax. Ternary expressions can be nested but avoid deep nesting for readability.
💻 Examples:
# Example 1: Basic ternary vs traditional if-else
# Traditional if-else (4 lines)
age = 25
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(status) # Adult
# Ternary — ONE LINE!
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
# More examples
number = 7
parity = "Even" if number % 2 == 0 else "Odd"
print(parity) # Odd
# Max of two numbers
a, b = 10, 20
maximum = a if a > b else b
print(maximum) # 20
# Absolute value
num = -15
abs_val = num if num >= 0 else -num
print(abs_val) # 15# Example 2: Employee data with ternary
employees = [
{"name": "Aarav", "salary": 50000, "experience": 2},
{"name": "Priya", "salary": 75000, "experience": 7},
{"name": "Kavya", "salary": 45000, "experience": 1}
]
for emp in employees:
# Level classification
level = "Senior" if emp["experience"] >= 5 else "Junior"
# Bonus calculation
bonus = emp["salary"] * 0.15 if emp["experience"] >= 5 else emp["salary"] * 0.05
# Tax bracket
tax = "High" if emp["salary"] > 70000 else "Low"
print(f"{emp['name']}: {level} | Bonus: ₹{bonus:.0f} | Tax: {tax}")
# Ternary in list comprehension
salaries = [emp["salary"] for emp in employees]
categories = ["High" if s > 60000 else "Low" for s in salaries]
print(categories) # ['Low', 'High', 'Low']# Example 3: Nested ternary (use carefully!)
# Grade based on marks — nested ternary
marks = 85
grade = "A" if marks >= 80 else "B" if marks >= 70 else "C" if marks >= 60 else "F"
print(f"Grade: {grade}") # Grade: A
# Same logic — traditional way is clearer for 3+ conditions
if marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
# Ternary in function calls / print()
name = "Aarav"
age = 25
print(f"{name} is {'adult' if age >= 18 else 'minor'}")
# Default value pattern (very common!)
skills = None
skills_list = skills if skills else ["General"]
print(skills_list) # ['General']
# Similar shortcut: 'or' operator (only for truthy check)
skills_list2 = skills or ["General"] # same result- Ternary sirf VALUE return karta hai — statements (print, assignment) directly nahi likh sakte.
- Nested ternary 2-3 levels tak ok, zyada = readability disaster. Traditional if-else use karo.
- Ternary
ifpehle aata hai, condition beech mein — C ke? :se different.
💬 Interview Q&A:
Q: Ternary operator kya hai aur kab use karna chahiye?
Ans: Ternary Python ka one-line if-else expression hai. Syntax: value_if_true if condition else value_if_false. Use karo: (1) Simple assignments jaise status = "Adult" if age >= 18 else "Minor". (2) List/dict comprehensions mein inline conditions. (3) Function arguments mein quick decisions. (4) Default values pattern. Avoid karo: (1) 3+ conditions — traditional if-elif better. (2) Complex logic — readability suffer. (3) Side effects (print, assignments in ternary) — sirf value return karo. Golden rule: agar one line mein clean lag raha hai, use karo; nahi toh if-else.
Q: Python ka ternary aur C ka ?: operator mein kya difference hai?
Ans: Syntax alag hai: C: condition ? true_val : false_val. Python: true_val if condition else false_val. Python ka syntax English jaisa readable hai — condition beech mein hai. C mein ternary compact hai but confusing ho sakta hai. Python design philosophy — "Readability counts". Behavior same hai — both return value based on condition. Python ka syntax intentional hai — beginner friendly aur code review mein clearly readable.
7. Logical Operators — and, or, not 🟡
📘 Definition: Logical operators combine multiple Boolean expressions. and — True if BOTH conditions True. or — True if AT LEAST ONE True. not — Reverses Boolean value. Python uses short-circuit evaluation — stops evaluating as soon as result is determined (performance optimization). Order of precedence: not > and > or.
📋 Truth Table:
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
💻 Examples:
# Example 1: Basic logical operators
age = 25
experience = 3
# AND — both must be True
if age >= 18 and experience >= 2:
print("Eligible for senior role") # both True → runs
# OR — at least one True
has_degree = False
has_certification = True
if has_degree or has_certification:
print("Qualified") # at least one True → runs
# NOT — reverses value
is_working = False
if not is_working:
print("On leave") # not False = True → runs
# Combining all three
age = 25
salary = 50000
is_active = True
if (age >= 18 and salary >= 40000) and not (age > 60):
print("Full-time employee")# Example 2: Short-circuit evaluation
# AND — stops at first False (skips rest)
def expensive_check():
print(" Checking expensive condition...")
return True
age = 15
if age >= 18 and expensive_check():
print("Adult")
# Output: (nothing — age < 18, expensive_check() NEVER called!)
# OR — stops at first True (skips rest)
if age < 18 or expensive_check():
print("Minor OR passed check")
# Output: "Minor OR passed check" — expensive_check() NEVER called!
# Practical: Safe division (avoid ZeroDivisionError)
numerator = 10
denominator = 0
# Short-circuit prevents division by zero
if denominator != 0 and numerator / denominator > 5:
print("Result is greater than 5")
else:
print("Cannot divide or result <= 5")
# Safe attribute check
employee = {"name": "Aarav"}
if "salary" in employee and employee["salary"] > 50000:
print("High earner")
else:
print("Salary not set or below 50k")# Example 3: Complex employee filtering
employees = [
{"name": "Aarav", "age": 25, "dept": "IT", "salary": 50000, "active": True},
{"name": "Priya", "age": 30, "dept": "HR", "salary": 75000, "active": True},
{"name": "Rahul", "age": 28, "dept": "Finance", "salary": 60000, "active": False},
{"name": "Vikram", "age": 35, "dept": "IT", "salary": 80000, "active": True}
]
# Filter: Active IT employees with salary > 55000
for emp in employees:
if emp["active"] and emp["dept"] == "IT" and emp["salary"] > 55000:
print(f"✅ {emp['name']} — qualified")
# Filter: HR OR Marketing department
for emp in employees:
if emp["dept"] == "HR" or emp["dept"] == "Marketing":
print(f"{emp['name']} — non-technical dept")
# NOT — filter inactive employees
inactive = [emp["name"] for emp in employees if not emp["active"]]
print(f"Inactive employees: {inactive}") # ['Rahul']
# Complex: (IT OR Finance) AND age < 30 AND active
for emp in employees:
if (emp["dept"] == "IT" or emp["dept"] == "Finance") and emp["age"] < 30 and emp["active"]:
print(f"Young tech/finance employee: {emp['name']}")• Short-circuit for safety:
if x != 0 and 10/x > 5: — division only if x != 0• Precedence: not > and > or — parentheses use karo clarity ke liye
• Membership check:
dept in ["IT", "HR"] better than multiple or• Chained comparisons:
18 <= age <= 60 — Pythonic aur clean💬 Interview Q&A:
Q: Short-circuit evaluation kya hai?
Ans: Short-circuit evaluation = logical operators result determine hote hi remaining conditions SKIP karte hain. and — first False mile toh baaki check nahi karta (final result False hi hoga). or — first True mile toh baaki skip (final result True). Fayde: (1) Performance — unnecessary computation avoid. (2) Safety — if x != 0 and 10/x > 5 — division only if safe. (3) Default values — value = arg or "default". Python, JS, C sab yeh use karte hain. Interview mein bahut asked topic hai.
Q: and, or, not ki precedence kya hai?
Ans: Precedence order (highest to lowest): not > and > or. Example: not True or False and True — pehle not True = False, phir False and True = False, phir False or False = False. Confusing? Isliye hamesha parentheses use karo: (not True) or (False and True) — explicit aur readable. PEP 8 recommendation: complex logical expressions mein parentheses use karo even if not needed. Bug source: precedence assumptions galat hone se logic break hoti hai.
8. for Loop — Iteration 🟡
📘 Definition: The for loop iterates over any ITERABLE (list, tuple, string, dict, set, range). Syntax: for variable in iterable:. On each iteration, variable takes the next value from iterable. Python's for loop is a "for-each" loop — no manual index management needed (unlike C/Java). Use range() for numeric loops, enumerate() for index+value, zip() for parallel iteration.
🎯 Samjho Hinglish Mein: for loop = "har item ke saath ye kaam karo". List of employees hai, har employee ka salary calculate karna hai → for loop. Range(10) hai, 10 baar kaam karna hai → for loop. Python ka for loop C/Java se easier hai — direct items iterate karta hai, index count karne ki tension nahi. Real-world: data processing ka 90% for loops se hi hota hai.
💻 Examples:
# Example 1: Basic for loop patterns
# Iterate list
names = ["Aarav", "Priya", "Rahul", "Neha"]
for name in names:
print(name)
# Iterate string (character by character)
for char in "Python":
print(char, end=" ") # P y t h o n
# range() — numeric loops
for i in range(5): # 0 to 4
print(i, end=" ") # 0 1 2 3 4
# range(start, stop)
for i in range(1, 6): # 1 to 5
print(i, end=" ") # 1 2 3 4 5
# range(start, stop, step)
for i in range(0, 11, 2): # 0, 2, 4, 6, 8, 10
print(i, end=" ")
# Reverse iteration
for i in range(10, 0, -1): # 10 to 1
print(i, end=" ")# Example 2: enumerate() and zip()
# enumerate — index + value
employees = ["Aarav", "Priya", "Rahul"]
for idx, name in enumerate(employees):
print(f"{idx}: {name}")
# 0: Aarav
# 1: Priya
# 2: Rahul
# enumerate with custom start
for idx, name in enumerate(employees, start=101):
print(f"Emp {idx}: {name}")
# Emp 101: Aarav
# Emp 102: Priya
# Emp 103: Rahul
# zip() — parallel iteration
names = ["Aarav", "Priya", "Rahul"]
salaries = [50000, 75000, 60000]
depts = ["IT", "HR", "Finance"]
for name, salary, dept in zip(names, salaries, depts):
print(f"{name} ({dept}): ₹{salary}")
# Iterate dictionary
employee = {"name": "Aarav", "age": 25, "dept": "IT"}
for key in employee: # keys only
print(key)
for key, value in employee.items(): # key + value
print(f"{key}: {value}")# Example 3: Real-world employee data processing
employees = [
{"name": "Aarav", "salary": 50000, "dept": "IT"},
{"name": "Priya", "salary": 75000, "dept": "HR"},
{"name": "Rahul", "salary": 60000, "dept": "Finance"},
{"name": "Neha", "salary": 55000, "dept": "IT"},
{"name": "Vikram", "salary": 80000, "dept": "Marketing"}
]
# Task 1: Calculate total salary
total = 0
for emp in employees:
total += emp["salary"]
print(f"Total salary: ₹{total}") # ₹320000
# Task 2: Count by department
dept_count = {}
for emp in employees:
dept = emp["dept"]
dept_count[dept] = dept_count.get(dept, 0) + 1
print(dept_count) # {'IT': 2, 'HR': 1, 'Finance': 1, 'Marketing': 1}
# Task 3: Give 10% raise to IT dept
for emp in employees:
if emp["dept"] == "IT":
emp["salary"] = int(emp["salary"] * 1.1)
print(f"{emp['name']} → New salary: ₹{emp['salary']}")
# Task 4: Find highest paid
highest = employees[0]
for emp in employees:
if emp["salary"] > highest["salary"]:
highest = emp
print(f"Highest paid: {highest['name']} — ₹{highest['salary']}")- Modifying list during iteration: Unpredictable behavior! Iterate over copy:
for x in list.copy(): - range() vs list: range is lazy (no memory), list stores all elements. Use range for large numbers.
- Don't manually index:
for i in range(len(list)):— bad. Usefor item in list:orenumerate().
💬 Interview Q&A:
Q: Python ka for loop C/Java ke for loop se kaise different hai?
Ans: Python ka for loop "for-each" style hai — directly iterables (list, tuple, dict, string) pe iterate karta hai. C/Java mein for(int i=0; i<n; i++) — manual counter chahiye. Python: for item in list: — clean aur Pythonic. Fayde: (1) Index management nahi, (2) Off-by-one errors kam, (3) Readable code, (4) Works with any iterable. Index chahiye toh enumerate() use karo. Numeric loops ke liye range(). Multiple lists parallel iterate karne ke liye zip(). Python style = more Pythonic, less error-prone.
Q: enumerate() aur zip() ka use kya hai?
Ans: enumerate(iterable, start=0) — iterable ke items ke saath index bhi deta hai. Use case: index track karna without manual counter — for i, item in enumerate(list):. zip(*iterables) — multiple iterables parallel iterate karta hai, tuples deta hai. Use case: do lists ek saath process karna — for name, age in zip(names, ages):. Different length lists — shortest tak hi iterate karta hai. Both are Pythonic — manual index arithmetic se better.
9. while Loop — Condition-Based Iteration 🟡
📘 Definition: The while loop repeats a code block AS LONG AS a condition is True. Syntax: while condition:. Condition is checked BEFORE each iteration. If condition never becomes False, it creates an infinite loop. Used when number of iterations is UNKNOWN in advance (input validation, event loops, game loops). Must manually update loop variable to avoid infinite loop.
📋 for vs while:
| Feature | for Loop | while Loop |
|---|---|---|
| Use When | Known iterations / iterable | Condition-based / unknown iterations |
| Control | Automatic (iterable exhausted) | Manual (condition update) |
| Infinite Loop Risk | Very low | High (if condition never False) |
| Example | Process list of employees | Input validation loop |
💻 Examples:
# Example 1: Basic while loops
# Simple counter
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # IMPORTANT: update variable, else infinite loop!
# Countdown
timer = 5
while timer > 0:
print(f"Time left: {timer}")
timer -= 1
print("Time up!")
# Sum of natural numbers 1-10
num = 1
total = 0
while num <= 10:
total += num
num += 1
print(f"Sum 1-10: {total}") # 55
# ❌ INFINITE LOOP — DANGER!
# while True:
# print("This never stops!")
# Use Ctrl+C to interrupt# Example 2: while with condition-based logic
# Password retry (simulated)
correct_password = "admin123"
attempts = 3
# Simulated user input (real app: input() function)
user_inputs = ["wrong1", "wrong2", "admin123"]
i = 0
while attempts > 0:
entered = user_inputs[i] # simulate input
print(f"Attempt {4-attempts}: {entered}")
if entered == correct_password:
print("✅ Access granted")
break
attempts -= 1
i += 1
if attempts == 0:
print("❌ Account locked")
# Process employees until budget exhausted
employees_queue = [
{"name": "Aarav", "bonus": 5000},
{"name": "Priya", "bonus": 7500},
{"name": "Rahul", "bonus": 6000},
{"name": "Neha", "bonus": 5500},
{"name": "Vikram", "bonus": 8000}
]
budget = 20000
processed = 0
while employees_queue and budget >= employees_queue[0]["bonus"]:
emp = employees_queue.pop(0)
budget -= emp["bonus"]
processed += 1
print(f"✅ {emp['name']} paid ₹{emp['bonus']} | Budget left: ₹{budget}")
print(f"\nProcessed: {processed} employees")
print(f"Remaining: {len(employees_queue)} employees")# Example 3: while True with break (event loop pattern)
# Menu-driven program simulation
menu_choices = ["1", "2", "3", "4"] # simulated inputs
i = 0
while True: # infinite loop, break to exit
if i >= len(menu_choices):
break
choice = menu_choices[i]
print(f"\nMenu: 1)View 2)Add 3)Update 4)Exit")
print(f"Your choice: {choice}")
if choice == "1":
print("Viewing employees...")
elif choice == "2":
print("Adding employee...")
elif choice == "3":
print("Updating employee...")
elif choice == "4":
print("Exiting... Goodbye!")
break # exit infinite loop
else:
print("Invalid choice")
i += 1
# Find first employee with salary > 70000
employees = [
{"name": "Aarav", "salary": 50000},
{"name": "Priya", "salary": 75000},
{"name": "Rahul", "salary": 60000}
]
i = 0
found = None
while i < len(employees):
if employees[i]["salary"] > 70000:
found = employees[i]
break
i += 1
print(f"Found: {found['name'] if found else 'None'}")• Iterations UNKNOWN in advance (input validation, retry logic)
• Event loops (game loops, server loops)
• Process until condition met (queue processing)
• Wait for external event (network response, file ready)
• 💡 Otherwise prefer
for loop — safer, cleaner💬 Interview Q&A:
Q: for aur while loop mein kya difference hai?
Ans: for loop: iterable ke over iterate karta hai — count known hai (list length, range). Loop variable automatic update. Safe — infinite loop rare. Use case: sequences process karna. while loop: condition True hone tak run karta hai — count unknown. Manual variable update zaroori. Infinite loop risk. Use case: input validation, event loops, wait patterns. Rule: agar iterable/count pata hai → for. Condition-based → while. Python mein for zyada common hai — 90% cases.
Q: Infinite loop kya hai aur kaise avoid karo?
Ans: Infinite loop = loop jo kabhi terminate nahi hoti — CPU 100% use, program hang. Cause: (1) Condition never False (while True: without break), (2) Variable update bhool jaana (while count < 10: without count += 1), (3) Logic error mein counter reset ho jaana. Avoid: (1) Always update loop variable, (2) break statement for exit conditions, (3) Test with small values first, (4) Use for loop when possible. Emergency: Ctrl+C to interrupt. Production mein timeout/max_iterations safety add karo.
10. break, continue, pass — Loop Control 🔴
📘 Definition: break — completely EXITS the loop immediately. continue — SKIPS current iteration, jumps to next. pass — does NOTHING, placeholder statement (useful for empty blocks, TODOs). All three work in both for and while loops. In nested loops, they only affect the INNERMOST loop.
📋 Comparison:
| Statement | Action | Use Case |
|---|---|---|
| break | Exit loop immediately | Found target, stop searching |
| continue | Skip to next iteration | Skip invalid data, filter |
| pass | Do nothing (placeholder) | Empty function/class body |
💻 Examples:
# Example 1: break — exit loop
# Find first even number
numbers = [1, 3, 5, 4, 7, 8]
for num in numbers:
if num % 2 == 0:
print(f"First even: {num}") # 4
break # exit immediately, don't check rest
# Find employee by name
employees = [
{"name": "Aarav", "id": 101},
{"name": "Priya", "id": 102},
{"name": "Rahul", "id": 103}
]
target = "Priya"
for emp in employees:
if emp["name"] == target:
print(f"Found {target} — ID: {emp['id']}")
break # stop searching once found
# Number guessing simulation
guesses = [50, 75, 42, 100]
secret = 42
for attempt, guess in enumerate(guesses, 1):
print(f"Attempt {attempt}: {guess}")
if guess == secret:
print(f"🎉 Correct in {attempt} attempts!")
break# Example 2: continue — skip iteration
# Print only odd numbers
for i in range(1, 11):
if i % 2 == 0:
continue # skip even numbers
print(i, end=" ") # 1 3 5 7 9
# Skip inactive employees
employees = [
{"name": "Aarav", "active": True, "salary": 50000},
{"name": "Priya", "active": False, "salary": 75000},
{"name": "Rahul", "active": True, "salary": 60000},
{"name": "Neha", "active": False, "salary": 55000}
]
total_active_salary = 0
for emp in employees:
if not emp["active"]:
continue # skip inactive, don't add to total
total_active_salary += emp["salary"]
print(f"Processing {emp['name']}: ₹{emp['salary']}")
print(f"\nTotal active salary: ₹{total_active_salary}") # ₹110000
# Data validation — skip invalid entries
raw_data = ["25", "abc", "30", "", "35", None, "28"]
valid_ages = []
for item in raw_data:
if not item or not isinstance(item, str):
continue
if not item.isdigit():
continue
valid_ages.append(int(item))
print(f"Valid ages: {valid_ages}") # [25, 30, 35, 28]# Example 3: pass — placeholder
# Empty function (TODO — implement later)
def calculate_tax(salary):
pass # TODO: implement tax logic
# Empty class
class Employee:
pass # TODO: add attributes
# Empty loop iteration (rarely useful, but valid)
for i in range(5):
if i == 3:
pass # do nothing when i is 3
else:
print(i)
# Handling all cases (some do nothing)
statuses = ["active", "inactive", "pending", "active"]
for status in statuses:
if status == "active":
print("Processing active")
elif status == "inactive":
print("Skipping inactive")
elif status == "pending":
pass # explicitly do nothing for pending (not implemented)
# break vs continue vs pass — key differences
for i in range(5):
if i == 2:
break # exits loop at i=2 → prints: 0, 1
print(i)
for i in range(5):
if i == 2:
continue # skips i=2 → prints: 0, 1, 3, 4
print(i)
for i in range(5):
if i == 2:
pass # does nothing → prints: 0, 1, 2, 3, 4 (all!)
print(i)💬 Interview Q&A:
Q: break, continue, pass mein kya difference hai?
Ans: break: loop se BAHAR nikalta hai — remaining iterations skip, loop terminate. continue: current iteration SKIP karta hai, next iteration start. Loop continue karta hai. pass: KUCH NAHI karta — placeholder, syntax fill karta hai. Loop normally continues. Example: for i in range(5): if i==2: break → 0,1. continue → 0,1,3,4. pass → 0,1,2,3,4. Use case: break = found target, continue = skip invalid, pass = TODO/empty block.
Q: Nested loops mein break/continue kaise kaam karte hain?
Ans: Both affect only INNERMOST loop — outer loop unaffected. Example: outer loop mein inner loop hai, inner mein break hai → sirf inner exit, outer continue. Outer loop se bhi bahar nikalna hai toh: (1) Flag variable use karo — found = True; break, phir outer mein check karke break. (2) Function mein wrap karke return use karo. (3) try-except with custom exception. Python mein "labeled break" nahi hai (unlike Java) — workaround chahiye. Design pattern: nested logic ko function mein extract karo cleaner code ke liye.
11. Nested Loops — Loops Inside Loops 🔴
📘 Definition: A Nested Loop is a loop INSIDE another loop. For each iteration of outer loop, inner loop runs COMPLETELY. Common uses: 2D grids/matrices, pattern printing, comparing every pair (all combinations), processing nested data structures. Performance: O(n × m) — bade data pe slow! Time complexity concern rakhna zaroori hai.
🎯 Samjho Hinglish Mein: Nested loops = loop ke andar loop. Sochho har day ke liye har employee ki attendance mark karni hai — outer loop days, inner loop employees. Total operations = days × employees. Bade data pe careful raho — 1000 × 1000 = 10 lakh operations, slow ho sakta hai. Matrix (2D grid), pattern printing, all pairs comparison — sab nested loops se hote hain.
💻 Examples:
# Example 1: Basic nested loops — multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}", end=" ")
print() # new line after each row
# Output:
# 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3
# 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
# 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
# Pattern printing — triangle
for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print()
# *
# * *
# * * *
# * * * *
# * * * * *
# 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print()# Example 2: Real-world — Attendance tracking
employees = ["Aarav", "Priya", "Rahul", "Neha"]
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
# Simulated attendance data (1 = present, 0 = absent)
attendance = [
[1, 1, 0, 1, 1], # Aarav
[1, 0, 1, 1, 1], # Priya
[0, 1, 1, 1, 0], # Rahul
[1, 1, 1, 1, 1] # Neha
]
# Print attendance report
for i, emp in enumerate(employees):
present_days = 0
for j, status in enumerate(attendance[i]):
if status == 1:
present_days += 1
percentage = (present_days / len(days)) * 100
print(f"{emp}: {present_days}/{len(days)} ({percentage:.0f}%)")
# Cross-department comparison
departments = {
"IT": ["Aarav", "Neha", "Rohan"],
"HR": ["Priya", "Kavya"],
"Finance": ["Rahul", "Suresh"]
}
for dept, emps in departments.items():
print(f"\n{dept} Department:")
for emp in emps:
print(f" - {emp}")# Example 3: Find pairs, break out of nested loops
# Find pairs with sum = 10
numbers = [1, 3, 5, 7, 9, 2, 8]
target = 10
pairs = []
for i in range(len(numbers)):
for j in range(i+1, len(numbers)): # avoid duplicates
if numbers[i] + numbers[j] == target:
pairs.append((numbers[i], numbers[j]))
print(f"Pairs summing to {target}: {pairs}")
# Pairs summing to 10: [(1, 9), (3, 7), (2, 8)]
# Employee salary comparison — who earns more than whom
employees = [
{"name": "Aarav", "salary": 50000},
{"name": "Priya", "salary": 75000},
{"name": "Rahul", "salary": 60000}
]
for emp1 in employees:
for emp2 in employees:
if emp1["name"] != emp2["name"] and emp1["salary"] > emp2["salary"]:
print(f"{emp1['name']} earns more than {emp2['name']}")
# Break out of nested loops — flag pattern
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
found = False
for row in matrix:
for element in row:
if element == target:
print(f"Found {target}!")
found = True
break # exits inner loop only
if found:
break # exits outer loop- Time complexity: Nested loops are O(n²) or worse. 1000×1000 = 10 lakh operations!
- Better alternatives:
setfor lookups (O(1)), dict for mappings, itertools for combinations. - Break inner only: break sirf innermost loop se bahar aata hai — flag pattern use karo dono se exit karne ke liye.
💬 Interview Q&A:
Q: Nested loop ka time complexity kya hota hai?
Ans: Nested loops ki time complexity O(n × m) hoti hai — outer n iterations, har outer iteration mein inner m iterations. Same size loops ke liye O(n²). Triple nested O(n³). Example: 1000 items ka nested loop = 10 lakh operations, 10000 items = 10 crore! Bade data pe extremely slow. Optimization: (1) Set/dict use karo lookups ke liye (O(1)), (2) Break early jab possible, (3) itertools use karo combinations ke liye, (4) NumPy/Pandas vectorized operations. Interview mein Big-O aware coder valued hote hain.
Q: Nested loops se dono se ek saath kaise bahar nikalein?
Ans: Python mein "labeled break" nahi hai (Java jaisa). Workarounds: (1) Flag variable: found = True; break, phir outer mein check karo. (2) Function extract: nested loops ko function mein daal do, return se dono exit. (3) Exception: custom exception raise karo aur outside catch karo (unpythonic but works). (4) itertools.product: nested loops flatten karke single loop. (5) List comprehension: simple cases ke liye. Cleanest approach: function + return.
12. else with Loops — for-else, while-else 🔴
📘 Definition: Python has a UNIQUE feature — else clause with loops! The else block executes ONLY if the loop completes NORMALLY (without hitting break). If loop is broken by break, else is skipped. This is one of Python's most confusing yet powerful features. Also called "no-break" clause because it runs when no break occurred.
🎯 Samjho Hinglish Mein: for-else / while-else = "loop bina break ke complete hui toh ye kaam karo". Confusing feature — beginners "else means loop khatam hone pe" samajhte hain (galat!). Actual meaning: "loop successfully complete hui, break nahi hua". Use case: search patterns — "found → break, not found → else". Interview mein bahut asked question hai — most Python developers ko yeh confuse karta hai!
💻 Examples:
# Example 1: Basic for-else behavior
# Case 1: No break — else RUNS
for i in range(5):
print(i, end=" ")
else:
print("Loop completed normally")
# Output: 0 1 2 3 4 Loop completed normally
# Case 2: With break — else SKIPPED
for i in range(5):
if i == 3:
break
print(i, end=" ")
else:
print("This will NOT print")
# Output: 0 1 2 (else skipped due to break)
# while-else — same behavior
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
else:
print("While loop finished cleanly")# Example 2: Practical use — search patterns
# Search for employee — traditional (using flag)
employees = ["Aarav", "Priya", "Rahul", "Neha"]
target = "Vikram"
found = False
for emp in employees:
if emp == target:
found = True
print(f"Found {target}")
break
if not found:
print(f"{target} not found")
# Same search — with for-else (Pythonic!)
for emp in employees:
if emp == target:
print(f"Found {target}")
break
else:
print(f"{target} not found") # runs because break didn't happen
# Check prime number
num = 17
for i in range(2, num):
if num % i == 0:
print(f"{num} is not prime (divisible by {i})")
break
else:
print(f"{num} is prime!") # else runs — no divisors found
# Validate all employees have salary > 0
employees_data = [
{"name": "Aarav", "salary": 50000},
{"name": "Priya", "salary": 75000},
{"name": "Rahul", "salary": 60000}
]
for emp in employees_data:
if emp["salary"] <= 0:
print(f"❌ Invalid: {emp['name']}")
break
else:
print("✅ All employees have valid salaries")# Example 3: Nested loops with for-else
# Find first employee with high salary in each department
company = {
"IT": [("Aarav", 50000), ("Neha", 55000), ("Rohan", 70000)],
"HR": [("Priya", 75000), ("Kavya", 45000)],
"Finance": [("Rahul", 60000), ("Suresh", 90000)]
}
threshold = 70000
for dept, emps in company.items():
for name, salary in emps:
if salary >= threshold:
print(f"{dept}: First high earner is {name} (₹{salary})")
break
else:
print(f"{dept}: No one above ₹{threshold}")
# Output:
# IT: First high earner is Rohan (₹70000)
# HR: No one above ₹70000
# Finance: First high earner is Suresh (₹90000)
# Check for duplicate skills across employees
employee_skills = {
"Aarav": ["Python", "SQL"],
"Priya": ["Excel", "Communication"],
"Rahul": ["Python", "Java"]
}
target_skill = "Python"
for emp, skills in employee_skills.items():
if target_skill in skills:
print(f"{emp} knows {target_skill}")
else:
# Note: This else runs when for completes normally, NOT when target found!
print(f"Loop completed — checked all employees")elseloop ke saath = "no break happened" — NOT "loop finished" (both actually true when no break).- Most Python developers avoid for-else due to confusion — traditional flag pattern more readable.
- Use case: search patterns —
breakon found,elsefor "not found" logic.
💬 Interview Q&A:
Q: for-else clause kya hai?
Ans: Python ka unique feature — else block loop ke baad execute hota hai ONLY IF loop bina break ke complete hui. Agar break hit hua, else skip. Syntax: for x in iter: ... else: .... Use case: search patterns — if found: break else: not_found_logic. Guido van Rossum (Python creator) ne kaha yeh naming misleading hai — actual meaning "no-break". Interview mein: "loop complete hui bina break ke". Confusing feature — most codebases mein rare use, but interviews mein frequently asked.
Q: for-else practical mein kab use karna chahiye?
Ans: Main use case: search patterns. Example: list mein item dhundhna — for item: if item == target: found; break; else: not_found. Elegant hai kyunki flag variable nahi chahiye. Prime number checking, validation loops, "any" operations mein useful. But most Python developers isse avoid karte hain due to confusion — traditional flag pattern (found = False) ya any()/all() built-in functions more readable. Personal recommendation: for-else jano interview ke liye, but production mein alternatives use karo readability ke liye.
13. Walrus Operator (:=) — Assignment Expressions 🔴
📘 Definition: The Walrus Operator := (introduced in Python 3.8) allows you to ASSIGN a value to a variable AS PART OF AN EXPRESSION. Named "walrus" because := looks like walrus eyes and tusks. Useful in while loops, list comprehensions, and if-statements to avoid computing the same value twice. Simplifies code where you'd otherwise assign then check.
🎯 Samjho Hinglish Mein: Walrus operator = "assign karo AUR use karo, ek line mein". Pehle assignment aur check alag lines mein karne padte the — ab ek line mein! Example: while (chunk := file.read(1024)): — chunk read karo, variable assign karo, aur while condition check karo — sab together. Python 3.8+ ka modern feature. Naam funny hai — := walrus ki aankhen aur daant jaisa dikhta hai! 🦭
💻 Examples:
# Example 1: Walrus in while loop (most common use)
# ❌ Traditional way (Python 3.7 and older)
data = [1, 2, 3, 4, 5]
value = data.pop() if data else None
while value is not None:
print(value, end=" ")
value = data.pop() if data else None
# Repetitive — value pop line 2 baar likhi
# ✅ With walrus operator (Python 3.8+)
data = [1, 2, 3, 4, 5]
while data and (value := data.pop()) is not None:
print(value, end=" ") # 5 4 3 2 1
# Reading file chunks (classic use case)
# Traditional
# with open("file.txt") as f:
# chunk = f.read(1024)
# while chunk:
# process(chunk)
# chunk = f.read(1024)
# With walrus — cleaner!
# with open("file.txt") as f:
# while chunk := f.read(1024):
# process(chunk)
# Simple example — input validation loop
inputs = ["invalid", "also_bad", "quit"]
i = 0
# Traditional:
# while True:
# user = input()
# if user == "quit": break
# process(user)
# With walrus:
# while (user := input()) != "quit":
# process(user)# Example 2: Walrus in if-statement (avoid duplicate computation)
# ❌ Traditional — len() called twice
employees = ["Aarav", "Priya", "Rahul", "Neha", "Vikram"]
if len(employees) > 3:
print(f"Team has {len(employees)} members")
# len() computed twice — inefficient for expensive functions
# ✅ With walrus — computed ONCE
if (n := len(employees)) > 3:
print(f"Team has {n} members") # n available in if block
# Real-world: expensive computation
def calculate_bonus(emp):
return emp["salary"] * 0.15 # imagine this is expensive
employee = {"name": "Aarav", "salary": 50000}
if (bonus := calculate_bonus(employee)) > 5000:
print(f"{employee['name']} qualifies for bonus: ₹{bonus}")
else:
print(f"Bonus too low: ₹{bonus}")
# Check dict value existence
data = {"salary": 50000}
if (sal := data.get("salary")) and sal > 40000:
print(f"Salary is high: ₹{sal}")# Example 3: Walrus in list/dict comprehensions
# Filter and transform — avoid double computation
employees = [
{"name": "Aarav", "salary": 50000},
{"name": "Priya", "salary": 75000},
{"name": "Rahul", "salary": 60000},
{"name": "Kavya", "salary": 45000}
]
# ❌ Traditional — bonus calculated twice per employee
result_bad = [
{"name": emp["name"], "bonus": emp["salary"] * 0.15}
for emp in employees
if emp["salary"] * 0.15 > 7000 # computed AGAIN
]
# ✅ With walrus — computed ONCE per employee
result_good = [
{"name": emp["name"], "bonus": bonus}
for emp in employees
if (bonus := emp["salary"] * 0.15) > 7000
]
print(result_good)
# [{'name': 'Priya', 'bonus': 11250.0}, {'name': 'Rahul', 'bonus': 9000.0}]
# Aggregate stats — process once, use multiple times
salaries = [emp["salary"] for emp in employees]
if (total := sum(salaries)) > 200000:
avg = total / len(salaries)
print(f"Total: ₹{total}, Average: ₹{avg:.0f}")
# Categorize employees with computed values
categories = {
emp["name"]: category
for emp in employees
if (category := "High" if emp["salary"] > 60000 else "Low")
}
print(categories)• while loops: reading data in chunks, input validation
• if statements: avoid computing same value twice
• Comprehensions: use computed value both in filter and result
• Regex matching:
if (m := re.match(pattern, s)):• 💡 Don't overuse — simple assignments zyada readable hain
💬 Interview Q&A:
Q: Walrus operator kya hai aur kab use karte hain?
Ans: Walrus operator := Python 3.8 mein aaya — assignment expression banata hai. Regular = statement hai, := expression hai (value return karta hai). Use cases: (1) while loops — assign and check in one line. (2) if statements — avoid duplicate computation. (3) Comprehensions — reuse computed values. Example: while (chunk := file.read(1024)): vs traditional 2-line pattern. Naam funny — := walrus eyes and tusks jaisa lagta hai. Controversial feature — Python creator Guido ne resign kar diya tha due to disagreement, but now widely accepted.
Q: = aur := mein kya difference hai?
Ans: =: assignment STATEMENT — variable ko value assign karta hai. Kuch return nahi karta. Standalone use hota hai: x = 5. Expressions mein use nahi kar sakte. :=: assignment EXPRESSION (walrus) — assign karta hai AUR value return karta hai. Expressions ke andar use kar sakte ho: if (n := len(x)) > 5. Python 3.8+ only. Regular assignments ke liye = use karo, jab expression mein bhi value chahiye tab :=. Rule: := hamesha parentheses mein safer hai — precedence confusion avoid.
14. match-case Statement — Pattern Matching 🔴
📘 Definition: match-case (Python 3.10+) is Python's version of switch statement — but MORE POWERFUL. It supports STRUCTURAL PATTERN MATCHING — not just value matching, but also patterns like sequences, dicts, classes, and destructuring. Cleaner alternative to long if-elif chains. Uses match to check a value against multiple case patterns. _ is the wildcard (default case).
💻 Examples:
# Example 1: Basic match-case (value matching)
department = "IT"
# Traditional if-elif
if department == "IT":
print("Coding project")
elif department == "HR":
print("Recruitment")
elif department == "Finance":
print("Budget analysis")
else:
print("General")
# Same with match-case (Python 3.10+)
match department:
case "IT":
print("Coding project")
case "HR":
print("Recruitment")
case "Finance":
print("Budget analysis")
case _: # default case (wildcard)
print("General")
# Multiple values in one case (using |)
grade = "A"
match grade:
case "A" | "B":
print("Excellent")
case "C" | "D":
print("Average")
case "F":
print("Fail")
case _:
print("Invalid grade")# Example 2: Advanced patterns — sequences and dicts
# Match with conditions (guards)
age = 25
match age:
case n if n < 18:
print("Minor")
case n if 18 <= n < 60:
print("Adult") # runs for 25
case n if n >= 60:
print("Senior")
# Match tuples / sequences
point = (0, 5)
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"On Y-axis at y={y}") # y captured
case (x, 0):
print(f"On X-axis at x={x}")
case (x, y):
print(f"Point at ({x}, {y})")
# Match dictionaries (destructuring!)
employee = {"name": "Aarav", "dept": "IT", "salary": 50000}
match employee:
case {"dept": "IT", "salary": sal} if sal > 45000:
print(f"IT employee, well-paid: ₹{sal}")
case {"dept": "HR"}:
print("HR employee")
case {"name": name}:
print(f"Employee: {name}")
case _:
print("Unknown data")# Example 3: Real-world — process employee actions
# API-like action processor
def process_action(action):
match action:
case {"type": "hire", "name": name, "dept": dept}:
return f"✅ Hired {name} in {dept}"
case {"type": "promote", "name": name, "level": level}:
return f"⬆️ Promoted {name} to {level}"
case {"type": "raise", "name": name, "amount": amt} if amt > 0:
return f"💰 {name} got raise: ₹{amt}"
case {"type": "terminate", "name": name, "reason": reason}:
return f"❌ Terminated {name} — reason: {reason}"
case _:
return "⚠️ Unknown action"
# Test with different actions
actions = [
{"type": "hire", "name": "Aarav", "dept": "IT"},
{"type": "promote", "name": "Priya", "level": "Manager"},
{"type": "raise", "name": "Rahul", "amount": 10000},
{"type": "terminate", "name": "Neha", "reason": "performance"},
{"type": "unknown"}
]
for action in actions:
print(process_action(action))
# Output:
# ✅ Hired Aarav in IT
# ⬆️ Promoted Priya to Manager
# 💰 Rahul got raise: ₹10000
# ❌ Terminated Neha — reason: performance
# ⚠️ Unknown action• Simple value check: Both similar, if-elif more compatible
• Complex patterns: match-case wins — destructuring, guards, class matching
• JSON/API data: match-case elegant — dict patterns built-in
• State machines: match-case cleaner than if-elif chains
• 💡 Python 3.10+ only — check version before using
💬 Interview Q&A:
Q: match-case aur switch statement (other languages) mein kya difference hai?
Ans: Python ka match-case traditional switch se BAHUT POWERFUL hai. Traditional switch (C, Java, JS) sirf value matching karta hai. Python ka match-case structural pattern matching karta hai: (1) Values — case "IT":. (2) Sequences — case (x, y):. (3) Dicts — case {"name": n}:. (4) Classes — case Point(x=0):. (5) Guards — case n if n > 5:. (6) OR patterns — case "A" | "B":. (7) Wildcard — case _:. Python 3.10+ mein aaya, inspired by Rust/Haskell.
Q: match-case use karna kab better hai?
Ans: Use match-case: (1) Structured data handle karna ho (JSON, API responses) — dict patterns clean hain. (2) Multiple distinct cases hain (5+ conditions) — if-elif chain lambi ho jaati. (3) Destructuring chahiye — automatic unpacking. (4) State machines implement karni hain. (5) Complex conditions with guards. Avoid if: (1) Simple 2-3 conditions — if-else better. (2) Python < 3.10 compatibility chahiye. (3) Team members familiar nahi hain — readability suffer. Modern Python codebases mein grow ho raha hai — future ka feature hai.
💬 Comments (0)
Loading comments...