Nested Conditional Statements

 Nested Conditions

The conditional block inside another if/else conditional block is called as nested conditional block. In the below example, Block 2 is nested conditional block and condition B is called nested conditional statement.

Code

matches_won = int(input())
goals = int(input())
if matches_won > 8:
if goals > 20:
print("Hurray")
print("Winner")
PYTHON

Input

10
22

Output

Hurray
Winner

Input

10
18

Output

Winner

Nested Condition in Else Block

We can also write nested conditions in Else Statement.

In the below example Block 2 is a nested conditional block.

Code

a = 2
b = 3
c = 1
is_a_greatest = (a > b) and (a > c)
if is_a_greatest:
print(a)
else:
is_b_greatest = (b > c)
if is_b_greatest:
print(b)
else:
print(c)
PYTHON
Collapse

Output

3

Elif Statement

Use the elif statement to have multiple conditional statements between if and else.

The elif statement is optional.

Multiple Elif Statements

We can add any number of

elif
statements after
if
conditional block.

Execution of Elif Statement

Python will execute the elif block whose expression evaluates to true.
If multiple

elif
conditions are true, then only the first elif block which is True will be executed.

Optional Else Statement

Else statement is not compulsory after

if - elif
statements.

Code

number = 5
is_divisible_by_10 = (number % 10 == 0)
is_divisible_by_5 = (number % 5 == 0)
if is_divisible_by_10:
print("Divisible by 10")
elif is_divisible_by_5:
print("Divisible by 5")
else:
print("Not Divisible by 10 or 5")
PYTHON

Output

Divisible by 5

Possible Mistake

Cannot write an elif statement after

else
statement.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form