Python Notes
Learn nested if statements in Python — placing if statements inside other if statements to handle complex, multi-level decision making. Includes real-world programs, flow diagrams, and Hindi explanations.
Introduction (परिचय)
Nested If का मतलब है — एक if statement के अंदर दूसरा if statement।
Real-Life Analogy: `` अगर (if) घर से बाहर जाना है: अगर (if) बारिश हो रही है: छाता लेकर जाओ नहीं तो: बिना छाते के जाओ नहीं तो: घर पर रहो ``Flow Diagram (प्रवाह आरेख)
Basic Examples (बुनियादी उदाहरण)
Example 1: Number Sign and Parity
num = int(input("Enter a number: "))
if num != 0:
print("Number is non-zero")
if num > 0:
print("Number is POSITIVE")
if num % 2 == 0:
print("AND it is EVEN")
else:
print("AND it is ODD")
else:
print("Number is NEGATIVE")
else:
print("Number is ZERO")Output (num = 6):
Output (num = -3):
Example 2: Student Result System
marks = int(input("Enter marks (0-100): "))
attendance = int(input("Enter attendance % (0-100): "))
if attendance >= 75:
print("Attendance: Eligible ✓")
if marks >= 33:
print("Result: PASS ✓")
if marks >= 90:
print("Grade: A+ — Outstanding!")
elif marks >= 75:
print("Grade: A — Excellent!")
elif marks >= 60:
print("Grade: B — Good!")
else:
print("Grade: C — Pass!")
else:
print("Result: FAIL ✗ (Marks below 33)")
else:
print("Attendance: NOT Eligible ✗")
print("Minimum 75% attendance required")
print("कम से कम 75% उपस्थिति जरूरी है")Output (marks=82, attendance=85):
| Attendance | Eligible ✓ |
| Result | PASS ✓ |
| Grade | A — Excellent! |
Output (marks=45, attendance=60):
Example 3: Bank Account Access
# Bank system with nested checks
account_active = True
username = input("Username: ")
pin = input("PIN: ")
if account_active:
if username == "rahul" and pin == "1234":
balance = 15000
print("\n✓ Login Successful!")
print("✓ लॉगिन सफल!")
action = input("\n1.Balance 2.Withdraw 3.Deposit\nChoice: ")
if action == "1":
print(f"Your balance: ₹{balance}")
elif action == "2":
amount = int(input("Enter amount: "))
if amount <= balance:
if amount > 0:
balance -= amount
print(f"₹{amount} withdrawn. Balance: ₹{balance}")
else:
print("Invalid amount!")
else:
print("Insufficient balance!")
print("अपर्याप्त राशि!")
else:
print("Invalid choice")
else:
print("✗ Invalid credentials!")
print("✗ गलत username या PIN!")
else:
print("Account is blocked. Contact bank.")
print("खाता बंद है। बैंक से संपर्क करें।")Indentation Levels (इंडेंटेशन स्तर)
Level 0: if outer: (0 spaces)
Level 1: if middle: (4 spaces)
Level 2: if inner: (8 spaces)
Level 3: code (12 spaces)# Visualizing indentation levels
x = 15
y = 8
z = 3
if x > 10: # Level 1 — 0 spaces
print("x > 10")
if y > 5: # Level 2 — 4 spaces
print(" y > 5")
if z > 0: # Level 3 — 8 spaces
print(" z > 0")
print(" All conditions met!")Output:
Real-World Programs (वास्तविक कार्यक्रम)
Program 1: E-commerce Order Eligibility
Program 2: Triangle Type Checker
Program 3: Job Application Filter
Program 4: Ticket Pricing System
print("=== Cinema Ticket Booking ===")
age = int(input("Enter age: "))
is_student = input("Are you a student? (yes/no): ").lower()
day = input("Day (weekday/weekend): ").lower()
show = input("Show (morning/afternoon/evening/night): ").lower()
# Base price
if age < 5:
print("FREE entry for children under 5! 🎈")
else:
if day == "weekend":
base_price = 200
print("Weekend pricing applied")
else:
base_price = 150
print("Weekday pricing applied")
# Show timing surcharge
if show == "night":
surcharge = 50
print("Night show surcharge: ₹50")
elif show == "evening":
surcharge = 25
print("Evening show surcharge: ₹25")
else:
surcharge = 0
total = base_price + surcharge
# Discount
if age >= 60:
discount = total * 0.30
print(f"Senior citizen 30% discount: ₹{discount:.0f}")
elif is_student == "yes":
discount = total * 0.20
print(f"Student 20% discount: ₹{discount:.0f}")
elif age < 12:
discount = total * 0.25
print(f"Child 25% discount: ₹{discount:.0f}")
else:
discount = 0
final = total - discount
print(f"\nTotal Ticket Price: ₹{final:.2f}")When NOT to Use Deep Nesting (गहरी nesting कब न करें)
# BAD — too deeply nested (hard to read)
if a:
if b:
if c:
if d:
if e:
print("Very deep!") # Hard to maintain
# BETTER — use logical operators
if a and b and c and d and e:
print("All conditions met!")
# BETTER — use early return (in functions)
def check(a, b, c):
if not a:
return "a failed"
if not b:
return "b failed"
if not c:
return "c failed"
return "All passed!"Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: Wrong Indentation Level
x = 10
y = 5
# WRONG — inner else aligned with outer if
if x > 5:
if y > 3:
print("Both true")
else: # This belongs to outer if, NOT inner if!
print("x <= 5")
# CORRECT — properly indented
if x > 5:
if y > 3:
print("Both true")
else: # Inner else — y <= 3
print("y <= 3")
else: # Outer else — x <= 5
print("x <= 5")❌ Mistake 2: Logic Error in Nesting Order
score = 45
paid_fee = False
# WRONG — checking score before fee payment
if score >= 33:
if paid_fee:
print("Certificate issued")
# Problem: score check should come AFTER fee check
# CORRECT — check prerequisite first
if paid_fee:
if score >= 33:
print("Certificate issued")
else:
print("Score too low")
else:
print("Please pay fee first")❌ Mistake 3: Missing else for inner if
# Can lead to silent logic errors
age = 25
income = 20000
if age >= 18:
if income >= 30000:
print("Loan approved")
# Missing else — no feedback when income < 30000!
# CORRECT
if age >= 18:
if income >= 30000:
print("Loan approved")
else:
print("Income insufficient")
else:
print("Age not eligible")Practice Exercises (अभ्यास प्रश्न)
Exercise 1 — Number Properties
Write a program that determines:
- Is the number positive, negative, or zero?
- If positive: is it even or odd?
- If positive and even: is it divisible by 4?
Exercise 2 — Login + Feature Access
| Level 1 | Check if user is logged in |
| Level 2 | Check if user is admin or regular |
| Level 3 | If admin — show admin panel |
| Level 4 | If premium — show all features |
Exercise 3 — Vehicle Registration
Check:
- Is the vehicle age <= 15 years? (eligible for road)
- If yes, has it passed pollution check?
- If yes, has insurance been paid?
- Only then: issue fitness certificate
Exercise 4 — School Admission
- Age 3-5: Nursery (if born before June)
- Age 5-6: KG
- Age 6-7: Class 1
- For each: check if documents are complete
Solutions (हल)
Solution 1 — Number Properties
num = int(input("Enter a number: "))
if num == 0:
print("Zero")
elif num > 0:
print("Positive")
if num % 2 == 0:
print("Even")
if num % 4 == 0:
print("Also divisible by 4")
else:
print("NOT divisible by 4")
else:
print("Odd")
else:
print("Negative")Solution 3 — Vehicle Registration
vehicle_age = int(input("Vehicle age (years): "))
pollution_cleared = input("Pollution check passed? (yes/no): ").lower()
insurance_paid = input("Insurance paid? (yes/no): ").lower()
if vehicle_age <= 15:
print("✓ Vehicle age OK")
if pollution_cleared == "yes":
print("✓ Pollution check cleared")
if insurance_paid == "yes":
print("✓ Insurance valid")
print("🎉 FITNESS CERTIFICATE ISSUED!")
print("फिटनेस प्रमाण पत्र जारी किया गया!")
else:
print("✗ Pay insurance first!")
else:
print("✗ Clear pollution check first!")
print("✗ पहले प्रदूषण जाँच पास करें!")
else:
print(f"✗ Vehicle too old ({vehicle_age} years). Max 15 years allowed.")
print("✗ वाहन बहुत पुराना है। अधिकतम 15 साल की सीमा।")Summary (सारांश)
| Concept | Description |
|---|---|
| Nested if | if के अंदर if |
| Indentation | हर level पर 4 spaces बढ़ता है |
| Execution | Outer True → check Inner |
| Use case | Multi-level decision making |
| Best practice | 3 levels से ज्यादा avoid करें |
Nesting Structure:
if (level 1):
if (level 2):
if (level 3): ← ideal max depth
code✅ Key Takeaways
- 🔹 Nested If का मतलब है एक
ifके अंदर दूसराif— inner condition तभी check होती है जब outer condition True हो - 🔹 Indentation is critical — हर nested level पर 4 spaces बढ़ते हैं, गलत indentation से logic बदल जाता है
- 🔹 No nesting limit — Python में technically कोई limit नहीं है, लेकिन 3 levels से ज्यादा avoid करें for readability
- 🔹 Outer → Inner flow — Python पहले outer condition evaluate करता है, True होने पर ही inner block में जाता है
- 🔹 else belongs to nearest if — indentation level से decide होता है कि
elseकिसifका है - 🔹 Use logical operators (
and,or) जब multiple conditions independently check करनी हों — unnecessary nesting avoid करें - 🔹 Early return pattern — functions में deeply nested if की जगह early
returnuse करें for cleaner code - 🔹 Always handle else cases — inner if में else missing होने से silent bugs आ सकते हैं, जो debug करना मुश्किल होता है
- 🔹 Real-world use cases — login systems, payment gateways, grading systems, e-commerce — सभी में nested if commonly use होता है
- 🔹 Testing tip — हर nested path को individually test करें — outer True + inner True, outer True + inner False, outer False
❓ FAQ
Q1: Nested if और elif में क्या difference है?
Answer: elif same level पर alternative conditions check करता है (mutually exclusive), जबकि nested if एक condition True होने के बाद उसके अंदर further conditions check करता है।
# elif — same level, alternative checks
if marks >= 90:
print("A+")
elif marks >= 75:
print("A")
# Nested if — deeper level, dependent checks
if marks >= 33:
if attendance >= 75:
print("Pass")Q2: Maximum कितने levels तक nest कर सकते हैं?
Answer: Python में technically कोई limit नहीं है — आप जितने चाहें levels nest कर सकते हैं। लेकिन best practice यह है कि 3 levels से ज्यादा nest न करें। ज्यादा nesting code को hard to read, debug, और maintain बनाती है। Deep nesting की जगह functions, logical operators, या early returns use करें।
Q3: Nested if में else कैसे पता करें कि किस if से belong करता है?
Answer: Python में indentation से decide होता है! else उस if से match करता है जो same indentation level पर हो। यही कारण है कि Python में indentation सिर्फ style नहीं, syntax है।
if x > 5:
if y > 3:
print("inner if")
else: # ← यह inner if (y > 3) का else है
print("inner else")
else: # ← यह outer if (x > 5) का else है
print("outer else")Q4: Nested if की जगह and operator use कर सकते हैं क्या?
Answer: हाँ! अगर आपको सिर्फ दोनों conditions True होने पर कुछ करना है, तो and operator use करें। लेकिन अगर different else blocks चाहिए (outer False vs inner False), तो nested if ज़रूरी है।
# Simple case — and works fine
if age >= 18 and has_license:
print("Can drive")
# Complex case — nested if needed
if age >= 18:
if has_license:
print("Can drive")
else:
print("Get a license first") # specific inner else
else:
print("Too young") # specific outer elseQ5: Nested if use करने का best time कब है?
Answer: Nested if तब use करें जब:
- Dependent conditions हों — second check first के True होने पर ही meaningful हो
- Different error messages — हर level पर अलग feedback देना हो
- Step-by-step validation — जैसे login → permission → action
- Hierarchical decisions — जैसे category → subcategory → item
Q6: क्या nested if से performance पर effect पड़ता है?
Answer: Performance effect negligible है! Python बहुत fast if checks करता है। Nested if actually efficient है क्योंकि inner conditions तभी evaluate होती हैं जब outer True हो — unnecessary checks skip हो जाती हैं। Performance issue सिर्फ readability और maintainability में होता है, execution speed में नहीं।
Q7: Function के अंदर nested if कैसे simplify करें?
Answer: Guard clause pattern (early return) use करें — पहले invalid cases handle करके return कर दें, फिर main logic लिखें:
# Instead of deeply nested:
def process_order(user, cart, payment):
if not user.is_logged_in:
return "Please login first"
if not cart.items:
return "Cart is empty"
if not payment.is_valid:
return "Invalid payment"
return "Order placed successfully! ✓"Q8: Nested if और nested ternary operator में difference?
Answer: Nested ternary (x if cond else y) one-liners के लिए है, लेकिन nested होने पर बहुत confusing हो जाता है। Complex logic के लिए हमेशा regular nested if-else use करें:
# Simple ternary — OK
result = "Pass" if marks >= 33 else "Fail"
# Nested ternary — AVOID (hard to read)
result = "A" if marks >= 90 else "B" if marks >= 75 else "C"
# Better — use regular nested if for complex logic🎯 Interview Questions
Q1: What is a nested if statement? Explain with example.
Answer: A nested if statement is an if statement placed inside another if statement. The inner if is only evaluated when the outer if condition is True. यह multi-level decision making के लिए use होता है।
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Bring your ID")
else:
print("Not eligible")Entry allowed
Use case: जब decision लेने के लिए multiple dependent conditions check करनी हों — जैसे पहले age verify करो, फिर documents check करो।
Q2: How does Python determine which else belongs to which if?
Answer: Python uses indentation (not braces like C/Java). An else matches the if at the same indentation level. This is Python's significant whitespace feature — indentation is part of the syntax, not just formatting.
Q3: What is the "dangling else" problem and how does Python solve it?
Answer: The "dangling else" problem occurs in languages like C/C++ where it's ambiguous which if an else belongs to. Python completely solves this problem through mandatory indentation — the else always pairs with the if at the same indent level. There is zero ambiguity.
Q4: When should you use nested if vs logical and operator?
Answer:
- Use
andwhen you only need one action for all-true case and don't need separate else handling - Use nested if when you need different else blocks at each level, or different error messages for each failed condition
# and — sufficient when single outcome needed
if username == "admin" and password == "1234":
print("Welcome")
# nested — needed when different failures need different messages
if username == "admin":
if password == "1234":
print("Welcome")
else:
print("Wrong password")
else:
print("User not found")Q5: What is the maximum nesting depth recommended? Why?
Answer: While Python has no hard limit, the recommended maximum is 3 levels. Beyond that:
- Code becomes hard to read and maintain
- Testing all paths becomes exponentially complex
- Indicates need for refactoring (extract functions, use guard clauses, logical operators)
PEP 8 and most style guides strongly recommend keeping code flat.
Q6: How can you refactor deeply nested if statements?
Answer: Multiple techniques:
- Guard clauses / Early returns — check failure cases first and return immediately
- Logical operators — combine simple conditions with
and/or - Extract functions — move inner logic into separate functions
- Dictionary dispatch — replace multiple conditions with a lookup table
- Match-case (Python 3.10+) — structural pattern matching for complex branching
Q7: In a nested if structure, if the outer condition is False, will the inner if be evaluated?
Answer: No, absolutely not. If the outer condition is False, Python skips the entire outer if block including all nested statements. This is called short-circuit evaluation at block level. Inner code is never reached, never evaluated — it's as if it doesn't exist for that execution path.
Q8: Write a nested if program to check if a year is a leap year.
Answer:
year = 2024
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year} is a Leap Year")
else:
print(f"{year} is NOT a Leap Year")
else:
print(f"{year} is a Leap Year")
else:
print(f"{year} is NOT a Leap Year")2024 is a Leap Year
Q9: What happens if you mix tabs and spaces in nested if indentation?
Answer: Python 3 raises a TabError: inconsistent use of tabs and spaces in indentation. Unlike Python 2, Python 3 strictly prohibits mixing tabs and spaces. Always use 4 spaces per indentation level (as per PEP 8). Most editors can be configured to convert tabs to spaces automatically.
Q10: Can you nest if statements inside else or elif blocks?
Answer: Yes! You can nest if inside else, elif, or even inside loops. The nesting is not limited to if-inside-if:
marks = 50
attendance = 80
if marks >= 33:
print("Marks OK")
else:
if attendance >= 90:
print("Grace marks given — Pass!")
else:
print("Fail — no grace possible")Marks OK
यह pattern तब useful है जब fail case में भी further decisions लेने हों।
Next Topic (अगला विषय)
➡️ For Loop — Python में repetition का जादू
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Nested If in Python.
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, control, flow, nested
Related Python Master Course Topics