0
0
Pythonprogramming~5 mins

Nested conditional execution in Python

Choose your learning style9 modes available
Introduction

Nested conditional execution helps you make decisions inside other decisions. It lets your program check more than one condition step by step.

When you want to check if a number is positive, and then check if it is even or odd.
When you ask a user for their age and then check if they are a child, teenager, or adult.
When you want to check if a password is correct and then check if the user has admin rights.
When you want to decide what to wear based on weather and then based on temperature.
Syntax
Python
if condition1:
    if condition2:
        # code if both conditions are true
    else:
        # code if condition1 is true but condition2 is false
else:
    # code if condition1 is false

Indentation is important to show which code belongs inside each condition.

You can nest as many if statements as you need, but keep it clear.

Examples
This checks if x is positive, then checks if it is even or odd.
Python
x = 10
if x > 0:
    if x % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")
This checks age groups by nesting conditions inside each other.
Python
age = 15
if age < 18:
    if age < 13:
        print("Child")
    else:
        print("Teenager")
else:
    print("Adult")
Sample Program

This program assigns a grade based on the score using nested conditions.

Python
score = 85
if score >= 60:
    if score >= 90:
        print("Grade: A")
    elif score >= 80:
        print("Grade: B")
    else:
        print("Grade: C")
else:
    print("Failed")
OutputSuccess
Important Notes

Too many nested conditions can make code hard to read. Try to keep it simple.

You can use elif inside nested conditions to check multiple cases.

Summary

Nested conditionals let you check one condition inside another.

Indentation shows which code belongs to which condition.

Use nested conditionals to handle complex decisions step by step.