Nested if else statement

Nested if else statements are used to execute different piece of code when we have more than two options to handle.

Example

Grade selection based on score.

Here, if our score is more than 90, we will get S grade

If our score is in between 80 and 90, we will get A grade

If our score is in between 70 and 80, we will get B grade

If our score is in between 60 and 70, we will get C grade

If our score is in between 51 and 60, we will get D grade

If our score is 50, we will get E grade

Below 50 will be declared as U.

Here, we have more than 2 options to handle.




Syntax

Example

if condition:
  #statement
elif condition:
  #statement
elif condition:
  #statement
else:
  #statement


It will check each condition sequentially and once the condition succeeds it goes to the corresponding block.

If none of them are true, then else code part will take place.




Sample Program

Get score from the user and display the grade based on above logic.

Example

#nested if else in python

score = int(input("Enter your score"))

if(score <=100 and score >= 90): 
  print("S")
elif(score < 90 and score >= 80):
  print("A")
elif(score < 80 and score >= 70):
  print("B")
elif(score < 70 and score >= 60):
  print("C")
elif(score < 60 and score > 50):
  print("D")
elif(score == 50):
  print("E")
elif(score < 50 and score >= 0):
  print("U")
else:
  print("Enter a valid score between 0 and 100")

The else: part is optional.