Python में Nested If
In this page:
if condition1:
if condition2:
# both are True
else:
# only condition1 is True
बेसिक Nested If Structure
एक if statement को दूसरे के indented body के अंदर रखने से nested if बनता है -- Python खुद indentation का इस्तेमाल करके तय करता है कि inner if किस block का हिस्सा है, इसलिए inner condition तक सिर्फ़ तभी पहुँचा जाता है जब outer condition पहले ही संतुष्ट हो चुकी हो।
उदाहरण: Basic Nested If Structure
age = 25
has_id = True
if age >= 18:
if has_id: # inner if only reached because the outer condition was True
print("Entry allowed")
Else Block के अंदर Nesting
nested if उतनी ही आसानी से else block के अंदर भी रह सकता है जितना if block के अंदर, जिससे आप outer condition की किस branch पर गए इस पर निर्भर करते हुए sub-cases का बिल्कुल अलग सेट संभाल सकते हैं।
उदाहरण: Nesting Inside an Else Block
logged_in = False
is_admin = False
if logged_in:
print("Welcome")
else:
if is_admin: # nested if inside the else branch
print("Admin fallback")
else:
print("Please log in")
कब Conditions को and से Combine करें
अगर कोई inner if तभी चलना चाहिए जब outer AND inner दोनों conditions True हों -- और "outer true, inner false" के लिए कोई खास handling न चाहिए हो -- तो उन्हें and से एक ही if में combine करना कम nesting और कम indentation के साथ बिल्कुल वही behavior देता है।
उदाहरण: When to Combine Conditions with and Instead
age = 20
has_ticket = True
if age >= 18 and has_ticket: # combines both checks into a single condition
print("Entry allowed")
Multi-Step Validation के लिए Nested If
Nested ifs स्वाभाविक रूप से तब फिट बैठते हैं जब हर validation step को पिछले step के पास होने के बाद ही चलना चाहिए -- जैसे किसी dictionary में key exists करने की पुष्टि करना, उसकी value की कोई property जाँचने से पहले, क्योंकि किसी missing चीज़ की property जाँचने से error आ सकता है।
उदाहरण: Nested If for Multi-Step Validation
user = {"name": "Alex"}
if "name" in user: # check the key exists before using it
if len(user["name"]) > 0:
print("Valid name:", user["name"])
Readability: Deep Nesting के विकल्प
दो या तीन levels के बाद, nested ifs को समझना सच में मुश्किल हो जाता है -- early returns (किसी condition के fail होते ही function से बाहर निकल जाना) या conditions को and से combine करने जैसी techniques गहराई से nested logic को ऊपर से नीचे स्कैन करने में कहीं आसान चीज़ में flatten कर सकती हैं।
उदाहरण: Readability: Alternatives to Deep Nesting
def check_access(age, has_id):
if age < 18:
return "Denied" # early return flattens the nesting
if not has_id:
return "Denied"
return "Allowed"
print(check_access(25, True))
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: