← Back to Python Course | Chapter 3: Control Flow | Lesson 3 of 10

Python में elif Ladder

elif ladder क्रम में पूछे गए सवालों की एक श्रृंखला जैसा है: क्या धूप है, क्या बादल हैं, क्या बारिश है? Python पहला सच जवाब लेता है और बाकी को नज़रअंदाज़ कर देता है।
Syntax
python
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

python
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

python
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

python
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

python
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

python
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")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.