Total Pageviews

Saturday, April 18, 2020

NESTED IF IN PYTHON

1. POSITIVE,NEGATIVE ZERO CHECKING - CLICK


📘 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 if is an if statement written inside another if block 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 elif sometimes

🆚 Nested if vs elif

FeatureNested ifelif
StructureInside another ifSame level
ComplexityHighLow
ReadabilityLowerBetter
UsageMultiple dependent checksMultiple independent checks

📌 Real-Life Example

  • Bank login system 🏦
  • Exam result system 📊
  • Eligibility checking 🎓
  • ATM PIN verification 💳

📘 Summary

  • Nested if means if inside if
  • Used for multiple condition checking
  • Helps in decision-making programs
  • Should be used carefully to avoid confusion

🧠 Important Questions

Short Questions

  1. What is nested if?
  2. Give syntax of nested if.
  3. Where is nested if used?
  4. Difference between if-elif and nested if.
  5. Give one example.

Long Questions

  1. Explain nested if with example.
  2. Write program for login system using nested if.
  3. Write program for largest of three numbers.
  4. Explain advantages and disadvantages of nested if.
  5. Write program for grading system using nested if. 

No comments:

Post a Comment