📘 Nested if in Python (Easy Explanation + Examples)
🎯 What is Nested if?
A nested if means an if statement inside another if statement.
It is used when we need to check multiple conditions step by step.
📌 Definition
Nested
ifis anifstatement written inside anotherifblock to check additional conditions.
🧠 Syntax
if condition1:
if condition2:
# code block
else:
# code block
else:
# code block
📊 Example 1: Check Number is Positive and Even
n = 10
if n > 0:
if n % 2 == 0:
print("Positive Even Number")
else:
print("Positive Odd Number")
else:
print("Negative Number")
📊 Example 2: Login System
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login Successful")
else:
print("Wrong Password")
else:
print("Invalid Username")
📊 Example 3: Largest of 3 Numbers
a = 10
b = 20
c = 15
if a > b:
if a > c:
print("A is largest")
else:
print("C is largest")
else:
if b > c:
print("B is largest")
else:
print("C is largest")
📊 Example 4: Voting Eligibility
age = 20
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
else:
print("Not a citizen")
else:
print("Not eligible")
📊 Example 5: Grade System
marks = 85
if marks >= 50:
if marks >= 80:
print("Grade A")
else:
print("Grade B")
else:
print("Fail")
⚡ Why Use Nested if?
- To check multiple conditions step by step
- To make decision trees
- To handle complex logic
❌ Disadvantages
- Code becomes complex
- Hard to read if too many levels
-
Can be replaced with
elifsometimes
🆚 Nested if vs elif
| Feature | Nested if | elif |
|---|---|---|
| Structure | Inside another if | Same level |
| Complexity | High | Low |
| Readability | Lower | Better |
| Usage | Multiple dependent checks | Multiple independent checks |
📌 Real-Life Example
- Bank login system 🏦
- Exam result system 📊
- Eligibility checking 🎓
- ATM PIN verification 💳
📘 Summary
-
Nested
ifmeansif inside if - Used for multiple condition checking
- Helps in decision-making programs
- Should be used carefully to avoid confusion
🧠 Important Questions
Short Questions
- What is nested if?
- Give syntax of nested if.
- Where is nested if used?
- Difference between if-elif and nested if.
- Give one example.
Long Questions
- Explain nested if with example.
- Write program for login system using nested if.
- Write program for largest of three numbers.
- Explain advantages and disadvantages of nested if.
- Write program for grading system using nested if.
No comments:
Post a Comment