Python – Nested if Statement

Python – Nested if Statement Explained with Examples

In Python, the nested if statement allows you to check for multiple conditions within a single if statement. It allows you to further refine the logic of your program by adding additional if statements inside the main if block.

Here is the basic syntax of a nested if statement in Python:

if condition1:
    # code to be executed if condition1 is true
    if condition2:
        # code to be executed if condition2 is true
        # additional nested if statements can be added here
    else:
        # code to be executed if condition2 is false
        # additional nested if statements can be added here
else:
    # code to be executed if condition1 is false

Let’s look at some examples to better understand the concept:

Example 1:

age = 25

if age > 18:
    print("You are an adult")
    if age > 25:
        print("You are over 25")
    else:
        print("You are between 18 and 25")
else:
    print("You are a minor")

In this example, the first if statement checks if the age is greater than 18. If it is true, it prints “You are an adult” and then checks if the age is greater than 25. If it is true, it prints “You are over 25”. If the age is not greater than 25, it prints “You are between 18 and 25”. If the age is not greater than 18, it prints “You are a minor”.

Example 2:

num = 10

if num % 2 == 0:
    print("The number is even")
    if num > 0:
        print("The number is positive")
    else:
        print("The number is negative")
else:
    print("The number is odd")

In this example, the first if statement checks if the number is even. If it is true, it prints “The number is even” and then checks if the number is greater than 0. If it is true, it prints “The number is positive”. If the number is not greater than 0, it prints “The number is negative”. If the number is not even, it prints “The number is odd”.

Nested if statements can be used to handle more complex conditions and provide a more granular control flow in your programs. However, it is important to keep the code clean and avoid excessive nesting, as it can make the code harder to read and maintain.

Remember, indentation is crucial in Python. Make sure to indent the code inside the if statements properly to indicate the nested structure.

That’s it! You now have a good understanding of nested if statements in Python and how to use them in your programs. Happy coding!

Scroll to Top