MWZ

MINDWAREZONE

Nested Conditions in python

Introduction

A Nested Condition in Python is an if statement placed inside another if, elif, or else block. Nested conditions are useful when a decision depends on multiple levels of checking.

For example, before allowing a student to take an exam, a program may first check if the student is registered and then check if the attendance requirement is met.

What is a Nested Condition?

A nested condition means one conditional statement is written inside another conditional statement.

Syntax

if condition1: 
    if condition2: 
        # code executes when both conditions are True
            

Key Points

  • An if statement can be placed inside another if, elif, or else block.
  • Used when multiple conditions must be checked in sequence.
  • Helps create more detailed decision-making logic.
  • Proper indentation is very important.
  • Avoid excessive nesting, as it can make code difficult to read.

Example 1: Voting Eligibility

age = 20 
citizen = True 

if age >= 18: 
   if citizen: 
       print("Eligible to vote")
            

Output

Eligible to vote
            

Explanation

The program first checks if the person is 18 or older. Then it checks if the person is a citizen. Since both conditions are true, the message is displayed.

Example 2: Student Exam Eligibility

registered = True 
attendance = 80 

if registered: 
    if attendance >= 75: 
        print("Eligible for exam") 
    else: 
        print("Attendance is too low") 
else: 
    print("Student is not registered")
            

Output

Eligible for exam
            

Explanation

The student is registered and has attendance above 75%, so the student can take the exam.

Example 3: Login and Admin Access

logged_in = True 
is_admin = False 

if logged_in: 
    if is_admin: 
        print("Admin Dashboard") 
    else: 
        print("User Dashboard") 
else: 
    print("Please Login")
            

Output

User Dashboard
            

Explanation

The user is logged in but is not an admin, so the User Dashboard is displayed.

Advantages of Nested Conditions

  • Handles complex decision-making.
  • Allows checking multiple requirements step by step.
  • Improves control over program flow.

Common Mistakes

  • Incorrect indentation.
  • Too many nested levels, making code difficult to understand.
  • Forgetting that inner conditions run only when outer conditions are true.