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:
- The outer
if
statement checks an initial condition (outer_condition
). - If the outer condition is
True
, the corresponding outer code block is executed. - Inside the outer code block, there's an inner
if
statement that checks another condition (inner_condition
). - If the inner condition is
True
, the corresponding inner code block is executed. - Optionally, an
else
block can be added for both the outer and innerif
statements to handle cases when the conditions areFalse
.
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.