Python From Beginner to Advanced

0% completed

Previous
Next
Python - elif Statement

The if-elif-else statement in Python is used when multiple conditions need to be checked. Instead of writing multiple if statements, we use elif (short for "else if") to check additional conditions. If the if condition is True, its block runs; otherwise, the program checks the elif conditions one by one. If none of the conditions are True, the else block executes.

Syntax

if condition1: # Code executes if condition1 is True elif condition2: # Code executes if condition1 is False and condition2 is True else: # Code executes if none of the above conditions are True
  • The if block is evaluated first.
  • If if is False, Python checks the elif conditions.
  • If no conditions are True, the else block executes.

Examples

Example 1: Checking Temperature Levels

Python3
Python3

. . . .

Explanation

  1. The variable temperature is set to 35.
  2. The first condition temperature >= 40 is False, so Python checks the next elif condition.

Example 2: Assigning Grades Based on Marks

Python3
Python3

. . . .

Explanation:

  1. The variable marks is set to 75.
  2. The first three conditions (marks >= 90, marks >= 80, and marks >= 70) are checked.
  3. Since marks >= 70 is True, that block executes, printing:
    Grade: C
    

The if-elif-else statement is useful when multiple conditions need to be checked in sequence. Instead of writing separate if statements, elif helps create a structured flow where only one condition executes. If none of the if or elif conditions are met, the else block provides a default action.

This approach makes the code more readable and efficient, reducing unnecessary checks. It is commonly used in scenarios like grading systems, temperature levels, and decision-based applications.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next