Python में if else: सशर्त कथन गाइड

स्पष्ट उदाहरणों के साथ Python if else कथनों में महारत हासिल करें। सिंटैक्स, सर्वोत्तम प्रथाएं और सामान्य उपयोग के मामलों को सीखें। इंटरैक्टिव कोड उदाहरण और ट्यूटोरियल शामिल हैं।

Python में if else कथन एक शर्त सच होने पर एक कोड ब्लॉक निष्पादित करके और शर्त गलत होने पर दूसरा ब्लॉक निष्पादित करके द्वि-दिशात्मक निर्णय लेने प्रदान करता है। एक साधारण if कथन के विपरीत जो शर्त गलत होने पर कुछ नहीं करता, if else यह सुनिश्चित करता है कि दो कोड पथों में से एक हमेशा निष्पादित होगा। यह ऐसे प्रोग्राम बनाने के लिए आवश्यक है जिन्हें सफलता और विफलता दोनों परिदृश्यों को संभालने की आवश्यकता होती है।

मूल if else सिंटैक्स

if else कथन शर्त False के रूप में मूल्यांकन होने पर एक वैकल्पिक क्रिया जोड़कर मूल if कथन का विस्तार करता है।

if condition:
    # code to execute if condition is True
    statement1
else:
    # code to execute if condition is False
    statement2

else कीवर्ड उस सभी को पकड़ता है जो if शर्त द्वारा पकड़ा नहीं गया है, if कथन द्वारा कवर नहीं किए गए परिदृश्यों के लिए "सब कुछ पकड़ने वाला" के रूप में कार्य करता है। Python if और else कीवर्ड के बाद एक कोलन (:) का उपयोग करता है, इसके बाद इंडेंटेड कोड ब्लॉक आते हैं।

उदाहरण 1: सरल if else कथन

a = 200
b = 33

if b > a:
    print("b is greater than a")
else:
    print("b is not greater than a")
आउटपुट:
b is not greater than a

Since 33 is not greater than 200, the condition is false, so the else block executes.

if else कैसे काम करता है

if else कथन एक सीधी निष्पादन प्रवाह का अनुसरण करता है:

  1. Python if कीवर्ड के बाद की शर्त का मूल्यांकन करता है
  2. यदि शर्त True है, तो पहला इंडेंटेड ब्लॉक निष्पादित होता है और else ब्लॉक छोड़ दिया जाता है
  3. यदि शर्त False है, तो पहला ब्लॉक छोड़ दिया जाता है और else ब्लॉक निष्पादित होता है
  4. किसी भी ब्लॉक के पूरा होने के बाद, निष्पादन पूरे if else संरचना के बाद के कोड के साथ जारी रहता है

उदाहरण: तापमान जांच

temperature = 15

if temperature > 20:
    print("It's warm outside")
else:
    print("It's cool outside")

print("Have a nice day!")
आउटपुट:
It's cool outside
Have a nice day!

अंतिम print कथन किसी भी शाखा को लिए जाने की परवाह किए बिना निष्पादित होता है।

if else के साथ मानों की तुलना करना

if else कथन आमतौर पर संख्यात्मक या स्ट्रिंग मानों के आधार पर निर्णय लेने के लिए तुलना ऑपरेटरों का उपयोग करता है।

उदाहरण 1: संख्या तुलना

number = 7

if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")
आउटपुट:
The number is odd

उदाहरण 2: स्ट्रिंग तुलना

username = "admin"

if username == "admin":
    print("Welcome, Administrator!")
else:
    print("Welcome, User!")
आउटपुट:
Welcome, Administrator!

उदाहरण 3: आयु सत्यापन

age = 16

if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote yet")
आउटपुट:
You are not eligible to vote yet

if else ब्लॉक में कई कथन

if और else दोनों ब्लॉक में कई कथन हो सकते हैं, जब तक वे सुसंगत इंडेंटेशन बनाए रखते हैं।

उदाहरण:

score = 85

if score >= 90:
    print("Excellent performance!")
    print("You earned an A grade")
    grade = "A"
    bonus_points = 10
else:
    print("Good effort!")
    print("Keep working hard")
    grade = "B"
    bonus_points = 5

print(f"Your grade is: {grade}")
print(f"Bonus points: {bonus_points}")
आउटपुट:
Good effort!
Keep working hard
Your grade is: B
Bonus points: 5

एक-पंक्ति if else (टर्नरी ऑपरेटर)

एकल कथनों वाली सरल शर्तों के लिए, Python आपको अधिक संक्षिप्त कोड बनाने के लिए एक पंक्ति पर if else लिखने की अनुमति देता है।

मानक प्रारूप:

age = 20

if age >= 18:
    status = "adult"
else:
    status = "minor"

print(status)

एक-पंक्ति प्रारूप (टर्नरी ऑपरेटर):

age = 20
status = "adult" if age >= 18 else "minor"
print(status)
आउटपुट:
वयस्क

More Examples:

# Example 1: Maximum of two numbers
a = 10
b = 20
max_value = a if a > b else b
print(f"Maximum: {max_value}")  # Output: Maximum: 20

# Example 2: Pass/Fail determination
marks = 75
result = "Pass" if marks >= 50 else "Fail"
print(result)  # Output: Pass

# Example 3: Sign determination
number = -5
sign = "Positive" if number > 0 else "Non-positive"
print(sign)  # Output: Non-positive

यह कॉम्पैक्ट सिंटैक्स सरल असाइनमेंट और त्वरित शर्तों के लिए विशेष रूप से उपयोगी है।

तार्किक ऑपरेटरों के साथ शर्तों को संयोजित करना

आप if else कथनों में जटिल शर्तें बनाने के लिए and, or और not ऑपरेटरों का उपयोग कर सकते हैं।

उदाहरण 1: and ऑपरेटर का उपयोग करना

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive")
else:
    print("You cannot drive")
आउटपुट:
You can drive

उदाहरण 2: or ऑपरेटर का उपयोग करना

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
else:
    print("It's a weekday")
आउटपुट:
It's the weekend!

उदाहरण 3: not ऑपरेटर का उपयोग करना

is_raining = False

if not is_raining:
    print("You don't need an umbrella")
else:
    print("Take an umbrella")
आउटपुट:
You don't need an umbrella

उदाहरण 4: तापमान सीमा जांच

temperature = 35

if temperature > 30 and temperature < 40:
    print("It's a hot day!")
else:
    print("Temperature is moderate")
आउटपुट:
It's a hot day!

नेस्टेड if else कथन

आप निर्णय लेने के कई स्तरों को संभालने के लिए अन्य if else कथनों के अंदर if else कथन रख सकते हैं।

उदाहरण 1: मूल नेस्टिंग

number = 10

if number >= 0:
    if number == 0:
        print("Number is zero")
    else:
        print("Number is positive")
else:
    print("Number is negative")
आउटपुट:
Number is positive

उदाहरण 2: नेस्टिंग के साथ ग्रेड वर्गीकरण

marks = 85

if marks >= 50:
    print("You passed!")
    if marks >= 90:
        print("Grade: A - Excellent!")
    else:
        print("Grade: B - Good job!")
else:
    print("You failed")
    print("Please retake the exam")
आउटपुट:
You passed!
Grade: B - Good job!

उदाहरण 3: बहु-स्तरीय उपयोगकर्ता प्रमाणीकरण

username = "admin"
password = "secret123"

if username == "admin":
    if password == "secret123":
        print("Access granted")
        print("Welcome to admin panel")
    else:
        print("Incorrect password")
else:
    print("User not found")
आउटपुट:
Access granted
Welcome to admin panel

हालांकि नेस्टिंग शक्तिशाली है, अत्यधिक नेस्टिंग कोड को पढ़ना मुश्किल बना सकती है—साफ़ बहु-शर्त तर्क के लिए elif का उपयोग करने पर विचार करें।

if else के साथ उपयोगकर्ता इनपुट सत्यापित करना

if else कथन इनपुट सत्यापन और त्रुटि हैंडलिंग के लिए आवश्यक है।

उदाहरण 1: खाली स्ट्रिंग जांच

username = ""

if len(username) > 0:
    print(f"Welcome, {username}!")
else:
    print("Error: Username cannot be empty")
आउटपुट:
Error: Username cannot be empty

उदाहरण 2: पासवर्ड लंबाई सत्यापन

password = "abc"

if len(password) >= 8:
    print("Password is valid")
else:
    print("Password must be at least 8 characters")
आउटपुट:
Password must be at least 8 characters

उदाहरण 3: संख्यात्मक सीमा सत्यापन

age = 150

if age > 0 and age <= 120:
    print(f"Age {age} is valid")
else:
    print("Invalid age entered")
आउटपुट:
Invalid age entered

उदाहरण 4: सूची सदस्यता जांच

allowed_users = ["alice", "bob", "charlie"]
current_user = "david"

if current_user in allowed_users:
    print("Access granted")
else:
    print("Access denied")
आउटपुट:
Access denied

elif के साथ विस्तार करना

हालांकि यह पृष्ठ if else पर केंद्रित है, आप क्रमिक रूप से कई शर्तों का परीक्षण करने के लिए if और else के बीच elif (else if) जोड़ सकते हैं।

temperature = 22

if temperature > 30:
    print("It's hot outside!")
elif temperature > 20:
    print("It's warm outside")
elif temperature > 10:
    print("It's cool outside")
else:
    print("It's cold outside!")
आउटपुट:
It's warm outside

else कथन अंत में आना चाहिए और जब कोई अन्य शर्त सच नहीं होती है तो डिफॉल्ट के रूप में कार्य करता है।

सामान्य उपयोग के मामले

उपयोग मामला 1: लॉगिन सिस्टम

stored_password = "python123"
entered_password = "python123"

if entered_password == stored_password:
    print("Login successful")
else:
    print("Invalid password")
आउटपुट:
Login successful

उपयोग मामला 2: छूट कैलकुलेटर

purchase_amount = 120

if purchase_amount >= 100:
    discount = purchase_amount * 0.10
    print(f"You get a 10% discount: ${discount}")
else:
    print("No discount available")
आउटपुट:
You get a 10% discount: $12.0

उपयोग मामला 3: पास/फेल सिस्टम

exam_score = 45
passing_score = 50

if exam_score >= passing_score:
    print("Congratulations! You passed")
else:
    print(f"Sorry, you need {passing_score - exam_score} more points to pass")
आउटपुट:
Sorry, you need 5 more points to pass

उपयोग मामला 4: फ़ाइल एक्सटेंशन चेकर

filename = "document.pdf"

if filename.endswith(".pdf"):
    print("This is a PDF file")
else:
    print("This is not a PDF file")
आउटपुट:
This is a PDF file

उपयोग मामला 5: लीप वर्ष चेकर

year = 2024

if year % 4 == 0:
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")
आउटपुट:
2024 is a leap year

बचने के लिए सामान्य गलतियां

गलती 1: कोलन भूल जाना

# Wrong
if number > 0
    print("Positive")
else
    print("Not positive")

# Correct
if number > 0:
    print("Positive")
else:
    print("Not positive")

गलती 2: असंगत इंडेंटेशन

# Wrong
if age >= 18:
    print("Adult")
else:
  print("Minor")  # Different indentation

# Correct
if age >= 18:
    print("Adult")
else:
    print("Minor")

गलती 3: else के बाद elif का उपयोग करना

# Wrong
if x > 0:
    print("Positive")
else:
    print("Not positive")
elif x < 0:  # SyntaxError
    print("Negative")

# Correct
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

गलती 4: खाली कोड ब्लॉक

# Wrong
if condition:
    # Code here
else:
    # This will cause an error

# Correct - use pass for placeholder
if condition:
    print("Condition met")
else:
    pass  # Do nothing

प्लेसहोल्डर के लिए pass का उपयोग करें

सर्वोत्तम प्रथाएं

अभ्यास 1: शर्तों को सरल और पढ़ने योग्य रखें

# Less readable
if not (age < 18 or not has_permission):
    print("Allowed")

# More readable
if age >= 18 and has_permission:
    print("Allowed")

अभ्यास 2: सार्थक चर नामों का उपयोग करें

# Poor
if x > 100:
    y = True

# Better
if purchase_amount > 100:
    eligible_for_discount = True

अभ्यास 3: दोनों पथों को स्पष्ट रूप से संभालें

# When both outcomes matter, use if else
file_exists = True

if file_exists:
    print("Loading file...")
else:
    print("Creating new file...")

जब दोनों परिणाम महत्वपूर्ण हों, तो if else का उपयोग करें

अभ्यास 4: गहरी नेस्टिंग से बचें

# Harder to read
if condition1:
    if condition2:
        if condition3:
            action()

# Better - use elif or logical operators
if condition1 and condition2 and condition3:
    action()

इसे स्वयं आज़माएं

if else कथनों के साथ प्रयोग करें

तैयार
main.py
आउटपुट कंसोल 0 ms
// परिणाम देखने के लिए "कोड चलाएं" पर क्लिक करें

संबंधित विषय

अक्सर पूछे जाने वाले प्रश्न

Python में if और if else के बीच क्या अंतर है?

एक if कथन केवल तभी कोड निष्पादित करता है जब शर्त सच होती है और अन्यथा कुछ नहीं करता। एक if else कथन यह गारंटी देता है कि दो कोड ब्लॉकों में से एक निष्पादित होगा—या तो if ब्लॉक जब शर्त सच हो या else ब्लॉक जब वह गलत हो।

क्या मैं elif के बिना एक if else रख सकता हूं?

हां, if else elif के बिना पूरी तरह से काम करता है। elif कीवर्ड केवल तब आवश्यक है जब आप क्रमिक रूप से कई शर्तों का परीक्षण करना चाहते हैं।

क्या मुझे Python if else कथनों में शर्तों के चारों ओर कोष्ठक का उपयोग करने की आवश्यकता है?

नहीं, कोष्ठक वैकल्पिक हैं। if (x > 5): और if x > 5: दोनों मान्य हैं, हालांकि बाद वाला Python में अधिक सामान्यतः उपयोग किया जाता है।

क्या मैं एक पंक्ति में if else का उपयोग कर सकता हूं?

हां, Python टर्नरी ऑपरेटर का समर्थन करता है: result = "yes" if condition else "no"। यह सरल असाइनमेंट के लिए उपयोगी है।

यदि मैं else ब्लॉक में कोड को इंडेंट करना भूल जाता हूं तो क्या होगा?

Python एक IndentationError उठाएगा क्योंकि इसे कोड ब्लॉक को परिभाषित करने के लिए सुसंगत इंडेंटेशन की आवश्यकता होती है।

क्या else if के बिना अपने आप दिखाई दे सकता है?

नहीं, else को हमेशा पिछले if कथन के साथ जोड़ा जाना चाहिए। आप else को स्वतंत्र रूप से उपयोग नहीं कर सकते।