Python में if-else Statement
In this page:
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
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
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
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
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
age = 20
has_id = True
if age >= 18 and has_id: # both conditions must be True
print("Entry allowed")
else:
print("Entry denied")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: