Nested IF In Python

There are situations when we need to check inside an if body other condition, means we will have other if on that body, or a nested if as often we see in programming terminology.

What if for our previous example about discount:

price=12

if  price >= 10:

discount=0.2

print("discount is higher")

else: 

discount=0.15

print("discount is smaller")

print(f"My discount is {discount}")

We need to give supplementary discount depending of the quantity, if price is greater than 10 and quantity is greater than 15 discount is higher with other 0.05 


Then sample code is: 

price=12

quantity=17

if  price >= 10:

discount=0.2

if quantity>15:

discount=discount+0.05

print("discount is higher")

else:

discount=0.15

print("discount is smaller")

print(f"My discount is {discount}")

Here commands executed in first if body are: 

discount=0.2

if quantity>15:

discount=discount+0.05

print("discount is higher")

here, inside it nested if is:

if quantity>15:

discount=discount+0.05

This is indented at the same level as the other commands, and the body of the nested if, I.e. discount=discount+0.05 is indented with one tab more.


In our example there is an if nested in if body, but it can also be inside else body, or inside of both if and else.

Below is an example:

price=7

quantity=17

if  price >= 10:

discount=0.2

if quantity>15:

discount=discount+0.05

print("discount is higher")

else:

discount=0.15

if quantity>15:

discount=discount+0.03

print("discount is corrected based on quantity")

print("discount is smaller")

print(f"My discount is {discount}")

and output of this is:

discount is corrected based on quantity

discount is smaller

My discount is 0.18


Process finished with exit code 0


A general syntax for nested if, with two levels nested is:

if conditionLevel1a: 

statements 

if conditionLevel2a: 

statements

elif conditionLevel2b: 

statements

else: 

statements 

elif conditionLevel1b: 

statements

else: 

statements


Or there can be:

if conditionLevel1a: 

statements 

elif conditionLevel1b: 

statements

if conditionLevel2a: 

statements

elif conditionLevel2b: 

statements

else:

statements 

else: 

statements

Obviously, there can be something similar having if inside else body. Also, in whatever cases from above we can have statements then nested if, or first to have nested if and then other statements.


We can have multiple nested levels, one general example for three level nested is: 

if conditionLevel1a: 

statements 

if conditionLevel2a: 

statements

if conditionLevel3a: 

statements

elif conditionLevel3b: 

statements

else:

statements 

elif conditionLevel2b: 

statements

else:

statements 

elif conditionLevel1b: 

statements

else: 

statements