Nested Conditions

Nested conditions mean using one if statement inside another if statement. This allows a program to check multiple levels of conditions before making a decision.

Nested conditions are useful when a second condition depends on the first condition.

SYNTAX OF NESTED IF

if condition1:
if condition2:
# code block

The second condition runs only if the first condition is True.

EXAMPLE 1: SIMPLE NESTED IF

age = 20
has_ticket = Trueif age >= 18:
if has_ticket:
print("You can enter the event.")

In this example:
• First, it checks if the person is 18 or older
• Then, it checks if the person has a ticket

Both conditions must be True to print the message.

EXAMPLE 2: NESTED IF WITH ELSE

age = 16
has_ticket = Trueif age >= 18:
if has_ticket:
print("You can enter.")
else:
print("You need a ticket.")
else:
print("You are underage.")

Here:
• If age is less than 18, it directly prints “You are underage.”
• If age is 18 or above, it checks for a ticket

NESTED IF WITH ELIF

marks = 85
attendance = 80if marks >= 50:
if attendance >= 75:
print("You passed the exam.")
else:
print("Insufficient attendance.")
else:
print("You failed the exam.")

This example checks:
• First → if the student passed the exam
• Second → if attendance requirement is met

IMPORTANT POINTS

• Proper indentation is very important
• Nested conditions increase logical control
• Avoid too many nested levels to keep code readable

WHEN TO USE NESTED CONDITIONS

• When a decision depends on another decision
• When validating multiple related conditions
• When building real-world applications like login systems, grading systems, or access control

Understanding nested conditions helps you write more powerful and logically structured Python programs.

Home » PYTHON FUNDAMENTALS (PYF) > Control Flow > Nested Conditions