Python – Nested If Else

Nested If Else in Python is an extension for the idea of if-else block. Any statement in the if or else blocks could be another if or if-else block. This makes nesting possible, and write an if or if-else inside if or else blocks.

In this tutorial, we will learn the syntax of Nested If Else statement, how to write a nested if-else statement, with the help of example Python programs.

Syntax

The following is the syntax of two level nested if-else statement.

</>
Copy
if <condition_1>:
    statement(s)
    if <condition_2>:
        statement(s)
    else:
        statement(s)
else:
    statement(s)

Nesting is not limited to two levels. You can write another if-else inside the inner if or else block. Then it would be three level nested if-else statement.

Example

In this example, we will write a nested if-else statement. If block contains an if-else statement inside it, and else block also contains an if-else block inside it.

The outer if-else block checks if the number n is even or odd. Inside outer if block, we have another if-else block with a condition that checks if the number n is exactly divisible by 10. Inside outer else block, we have an if-else statement with condition to check if n is exactly divisible by 5.

example.py – Python Program

</>
Copy
n = 15

if n%2 == 0:
	print(f'{n} is even.')
	if (n%10 == 0):
		print(f'{n} is divisible by 10.')
	else:
		print(f'{n} is not divisible by 10.')
else:
	print(f'{n} is odd.')
	if (n%5 == 0):
		print(f'{n} is divisible by 5.')
	else:
		print(f'{n} is not divisible by 5.')

Output

15 is odd.
15 is divisible by 5.

Conclusion

In this Python Tutorial, we have learnt Nested If Else statement, and how any statement in if block or else block could be another if or if-else conditional statement.