CodeSutraHub

if-elif-else Ladder in Python

Here we will learn about the third type of conditional statement, called the if-elif-else ladder.

if-elif-else Ladder in Python

The if-elif-else ladder is used to check multiple conditions one by one. It executes the code block associated with the first condition that evaluates to True. If none of the conditions are True, the else block is executed.

Syntax:

if condition1:
    statements executed if condition1 is True
elif condition2:
    statements executed if condition2 is True
elif condition3:
    statements executed if condition3 is True
else:
    default statements if no condition is True
In the above syntax, condition1, condition2, and condition3 are Boolean expressions. First, condition1 is checked. If it is True, the associated block is executed. If condition1 is False, condition2 is checked. If condition2 is True, its associated block is executed. This process continues until a True condition is found. If all conditions are False, the else block is executed. An if-elif-else ladder can contain any number of elif conditions.

Algorithm to Check Student Grade


Step 1: Start
Step 2: Read marks
Step 3: If marks >= 75
            Print "Distinction"
            Go to Step 8
Step 4: Else if marks >= 60
            Print "First Class"
            Go to Step 8
Step 5: Else if marks >= 50
            Print "Second Class"
            Go to Step 8
Step 6: Else if marks >= 35
            Print "Pass"
            Go to Step 8
Step 7: Else
            Print "Fail"
Step 8: Stop

The following program demonstrates the if-elif-else ladder in Python


# Example of if-elif-else ladder in Python
marks = 67

if marks >= 75:
    print("Distinction")
elif marks >= 60:
    print("First Class")
elif marks >= 50:
    print("Second Class")
elif marks >= 35:
    print("Pass")
else:
    print("Fail")
Output:
First Class
  • marks = 67:
    Student marks are assigned as 67.
  • if marks >= 75:
    67 is not greater than or equal to 75, so this condition is False.
  • elif marks >= 60:
    67 is greater than or equal to 60, so this condition is True. Hence, "First Class" is printed.
  • elif marks >= 50:
    This condition is not checked because a previous condition is already True.
  • elif marks >= 35:
    This condition is also skipped for the same reason.
  • else:
    The else block runs only if all conditions are False, which is not the case here.

What We Have Learned So Far

  • Learned about the if-elif-else ladder
  • Wrote and understood a program using the if-elif-else ladder
  • Bitwise Operators will be covered in the next topic

Below Video Explains if-elif-else Ladder in Python