Python में elif Ladder
In this page:
if condition1:
# block 1
elif condition2:
# block 2
else:
# default block
बेसिक Elif Structure
elif ladder कई conditions को एक साथ जोड़ता है और उन्हें ऊपर से नीचे जाँचता है, केवल उसी पहले block को चलाता है जिसकी condition True है और उसके बाद की हर condition को skip कर देता है, भले ही कोई बाद वाली condition भी match करती हो।
उदाहरण: Basic Elif Structure
score = 75
if score >= 90:
print("A")
elif score >= 70: # only checked because the first condition was False
print("B")
else:
print("C")
कई Elif Blocks
आप एक if और एक वैकल्पिक अंतिम else के बीच जितने चाहें उतने elif blocks जोड़ सकते हैं, जो किसी value को कई अलग-अलग categories या ranges में classify करने का standard तरीका है।
उदाहरण: Multiple Elif Blocks
temp = 15
if temp >= 30:
print("Hot")
elif temp >= 20:
print("Warm")
elif temp >= 10: # this is the first condition that matches
print("Cool")
else:
print("Cold")
Condition के क्रम का महत्व
क्योंकि Python पहली True condition पर रुक जाता है, क्रम मायने रखता है: एक broad condition (जैसे score >= 60) को एक narrower, ज़्यादा specific condition (जैसे score >= 90) से पहले रखने का मतलब है कि narrower branch कभी नहीं पहुँच पाएगा।
उदाहरण: Importance of Condition Order
score = 95
if score >= 60: # this broad condition matches first
print("Pass")
elif score >= 90:
print("This never runs") # unreachable because the elif above it already caught this
Default Fallback वाली Ladder
अंत का else block उन सभी cases को पकड़ता है जिन्हें पहले की किसी condition ने match नहीं किया, यह एक safety net की तरह काम करता है ताकि ladder किसी अनजान input पर भी हमेशा कोई न कोई result दे।
उदाहरण: Ladder with Default Fallback
day = "Funday"
if day == "Saturday":
print("Weekend")
elif day == "Sunday":
print("Weekend")
else:
print("Unknown day") # fallback for any day not matched above
Logical Elif जाँच
हर elif condition खुद भी and/or से कई जाँचों को जोड़ सकती है, जिससे एक ही ladder branch कई related inputs को एक साथ संभाल सकती है, बजाय इसके कि हर combination के लिए अलग elif चाहिए हो।
उदाहरण: Logical Elif Checks
age = 25
has_ticket = True
if age < 12:
print("Child rate")
elif age >= 65 or has_ticket: # combines two checks in one elif
print("Discount rate")
else:
print("Full price")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: