Python Nested if...else
Nested if...else
allows you to write one if
or else
block inside another. It is used when decisions depend on multiple conditions step-by-step.
Nested if...else
में एक if
या else
के अंदर दूसरा if
या else
होता है। इसका उपयोग तब होता है जब निर्णय कई शर्तों पर आधारित हो।
Why Use Nested if...else?
- To check multiple related conditions in steps.
- To handle complex logic with clarity.
- To create real-world decision structures (like form validation, grade system, etc.).
- To make your code more readable and logical.
- Essential for scenarios where one decision depends on another.
Example 1: Grade Evaluation
marks = 85
if marks >= 60:
if marks >= 90:
print("Grade A")
else:
print("Grade B")
else:
print("Fail")
Output:
Grade B
Checks if marks are above 60, then further checks for Grade A or B.
60 से ऊपर होने पर ग्रेड A या B की जांच करता है।
Example 2: Voting Eligibility
age = 20
id_card = 'yes'
if age >= 18:
if id_card == 'yes':
print("You can vote.")
else:
print("ID required to vote.")
else:
print("Not eligible.")
Output:
You can vote.
Checks age and ID card before allowing to vote.
वोट देने के लिए आयु और ID कार्ड की जांच करता है।
Example 3: Number Sign
num = 0
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive")
else:
print("Negative")
Output:
Zero
Checks if a number is positive, negative, or zero.
संख्या positive, negative या zero है यह जांचता है।
Example 4: Login Check
username = 'admin'
password = '1234'
if username == 'admin':
if password == '1234':
print("Login Successful")
else:
print("Incorrect Password")
else:
print("Invalid Username")
Output:
Login Successful
Checks username and then password for login.
पहले username फिर password की जांच करता है।
Example 5: Check Even or Odd and Divisibility
num = 12
if num % 2 == 0:
if num % 3 == 0:
print("Even and divisible by 3")
else:
print("Even but not divisible by 3")
else:
print("Odd number")
Output:
Even and divisible by 3
Checks if number is even and divisible by 3.
संख्या even और 3 से विभाजित है या नहीं यह जांचता है।