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

Python में if-else Statement

if-else एक रास्ते के दो मोड़ की तरह है: अगर condition true है तो आप एक तरफ़ जाते हैं, वरना दूसरी तरफ़। इन दोनों में से हमेशा exactly एक रास्ता ही चलता है।
Syntax
python
if condition:
    # code if True
else:
    # code if False

Standard If-Else

if/else statement दो में से exactly एक code path चुनता है: if block तब चलता है जब condition True हो, और else block जब भी condition False हो तो अपने-आप चलता है -- हर input एक न एक branch से ज़रूर गुज़रता है, दोनों से कभी नहीं।

उदाहरण: Standard If-Else

python
age = 15
if age >= 18:
    print("Adult")
else:
    print("Minor")  # runs because age >= 18 is False

Boolean Flag की जाँच

if/else को boolean flag variable के साथ जोड़ना एक साफ़-सुथरा toggle या gate बनाता है -- उदाहरण के लिए, if is_logged_in: बनाम else: -- जो पढ़ने में स्वाभाविक लगता है और program state की जाँच को एक नज़र में समझना आसान बनाता है।

उदाहरण: Boolean Flag Checks

python
is_logged_in = False
if is_logged_in:
    print("Welcome back")
else:
    print("Please log in")  # runs because the flag is False

If-Else से Variable Assignment

किसी condition के आधार पर variable की value assign करना, जैसे status = "adult" if age >= 18 else "minor", एक common pattern है जिससे आप बिना multi-line block के आसपास के logic को उलझाए एक value से दूसरी value निकाल सकते हैं।

उदाहरण: Variable Assignment with If-Else

python
age = 16
status = "adult" if age >= 18 else "minor"  # derive status from age in one line
print(status)

Strings के साथ Logic

in keyword condition के अंदर सीधे membership जाँचता है -- if "@" in email: -- जिससे आप यह देख सकते हैं कि कोई substring, character या item किसी string, list या अन्य collection में है या नहीं, बिना किसी अलग search step के।

उदाहरण: Logic with Strings

python
email = "[email protected]"
if "@" in email:  # membership check for a substring
    print("Looks like a valid email")
else:
    print("Missing @ symbol")

Logical Operators को मिलाना

एक ही if/else condition के अंदर and/or से कई जाँचों को मिलाना -- जैसे if age >= 18 and has_id: -- आपको कई अलग-अलग if statements नेस्ट किए बिना एक साथ कई criteria पर branch को gate करने देता है।

उदाहरण: Combining Logical Operators

python
age = 20
has_id = True
if age >= 18 and has_id:  # both conditions must be True
    print("Entry allowed")
else:
    print("Entry denied")
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.