Nested-if statement in Python
Last Updated :
08 May, 2024
There comes a situation in real life when we need to make some decisions and based on these decisions, we decide what we should do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we choose when to execute the next block of code. This is done with the help of a Nested if statement.
Python Nested if Statement
In Python a Nested if statement, we can have an 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.
Flow Chart of Nested if Statement
We can use a simple Python if statement inside another if or if…else statement. It can be used to check multiple if statements. In this case, an if condition is present inside another if conditions. We can have multiple if conditions inside an if condition. The inner if condition will only be executed if and only if the outer if condition is True.
Python if Statement
In this example, first we will check if a number is not equal to zero using the if condition. If it returns True, then we will check if the number is positive, that is, the number is greater than 0.
Syntax
if(condition):
{
// if body
// Statements to execute if condition is true
}
Python
# Python code to demonstrate the syntax of if statement
gfg = 9
# if statement with true condition
if gfg < 10:
print(f"{gfg} is less than 10")
# if statement with false condition
if gfg > 20:
print(f"{gfg} is greater than 20")
Output:
9 is less than 10
Multiple IF Statements in Python
In this example, we will see how we can use multiple if statements nested inside a single if statement to check multiple conditions. We will take the previous example, but this time we will check for two conditions where the number is positive or negative.
Syntax
if (condition1):
# executes when condition is True
if (condition2):
# executes when condition is True
Python
# Python program to demonstrate
# nested if with multiple if statements
i = -15;
# condition 1
if i != 0:
# condition 2
if i > 0:
print("Positive")
# condition 3
if i < 0:
print("Negative")
Output:
Negative
Nested if Statement With else Condition
We can also nest an if statement inside and if else statement in Python. In this example, we will first check if the number is not equal to 0. If it returns True, then we will check if the number if Positive or Negative. If the first If condition returns False, its code block will not execute and the else part of the Python if else statement will execute.
Python
i = 0;
# if condition 1
if i != 0:
# condition 1
if i > 0:
print("Positive")
# condition 2
if i < 0:
print("Negative")
else:
print("Zero")
Output:
Zero