🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Nested if Statement

Python Nested if Statement

Python Nested if Statement

In Python, a nested if statement is an if statement that appears inside another if statement. This allows you to check for multiple conditions in a hierarchical manner. The basic syntax of a nested if statement is as follows:

if outer_condition:
    # Outer code block
    if inner_condition:
        # Inner code block
    else:
        # Inner else code block
else:
    # Outer else code block (optional)

Here's a more detailed breakdown:

  1. The outer if statement checks an initial condition (outer_condition).
  2. If the outer condition is True, the corresponding outer code block is executed.
  3. Inside the outer code block, there's an inner if statement that checks another condition (inner_condition).
  4. If the inner condition is True, the corresponding inner code block is executed.
  5. Optionally, an else block can be added for both the outer and inner if statements to handle cases when the conditions are False.

Example:

x = 10
y = 5

if x > 5:
    print("Outer condition is true.")
    
    if y > 0:
        print("Inner condition is true.")
    else:
        print("Inner condition is false.")
else:
    print("Outer condition is false.")

In this example, the outer if statement checks if x is greater than 5. If it's True, the corresponding outer code block is executed, and inside that block, there's an inner if statement checking if y is greater than 0. The output depends on both conditions.

Nested if statements are useful when you need to evaluate conditions in a hierarchical manner, with certain conditions only being checked if other conditions are met. However, excessive nesting can lead to code that is harder to read and understand, so it's important to use them judiciously.

Example with Nested if-elif-else:

x = 10

if x > 5:
    print("x is greater than 5.")
    
    if x == 10:
        print("x is equal to 10.")
    elif x > 10:
        print("x is greater than 10.")
    else:
        print("x is less than 10.")
else:
    print("x is not greater than 5.")

In this example, there's an outer if-else statement, and if the outer condition is True, an inner if-elif-else statement is evaluated. This structure allows for more complex decision-making based on multiple conditions.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.