Python Nested if Statement

There may be a situation when we can check for another condition after a condition resolves to true. In such a situation, we can use the nested if construct.  A if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can.

Syntax:

if (expression1):
    (statement)
    if (expression2):
        (statement)
    elif (expression3):
        (statement)
    elif (expression4):
        (statement)
    else:
        (statement)
else:
    (statement)

Flow Chart:

Python Nested if statement

Example:

x = 53

if x > 10:
    print("Above ten,")
    if x > 20:
        print("and also above 20!")
    else:
        print("but not above 20.")
else:
    print("Less than 10")

Output:

Above ten,
and also above 20!
Tags