Nested-if Statement In Python

Nested-if Statement

One conditional can also be nested within another. ie, We can have a 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.

General Syntax of Nested if..else statement is

 if TEST EXPRESSION1:
 	if TEST EXPRESSION2:
 		STATEMENTS_B
 	else:
 		STATEMENTS_C
 else:
 	if TEST EXPRESSION3:
 		STATEMENTS_D
 	else:
 		STATEMENTS_E

Flowchart

python-nested-if

The outer conditional contains two branches. Those two branches contain another if… else statement, which has two branches of its own. Those two branches could contain conditional statements as well.

Example:

 a=10
 b=20
 c=5
 if a>b:
     if a>c:
         print("Greatest number is ",a)
     else:
         print("Greatest number is",c)
 else:
     if b>c:
         print("Greatest number is ",b)
     else:
         print("Greatest number",c)

Output:

 Greatest number is  20

Although the indentation of the statements makes the structure apparent, nested conditionals very quickly become difficult to read. In general, it is a good idea to avoid them when yo can.


Read Also: