MWZ

MINDWAREZONE

Elif Statement in python

Introduction

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".  

The elif keyword allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

Syntax

if condition1: 
    # code block 1 
elif condition2: 
    # code block 2 
            

Key Points

  • elif means else if.
  • Used to test multiple conditions.
  • Can have multiple elif blocks.
  • Python checks conditions from top to bottom.
  • Once a condition is True, the remaining conditions are skipped.

Example 1: Grade Calculator

marks = 85 

if marks >= 90: 
    print("Grade A") 
elif marks >= 75: 
    print("Grade B") 
elif marks >= 60: 
    print("Grade C") 
            

Output

Grade B
            

Explanation

The first condition is False, but marks >= 75 is True, so Python prints Grade B.

Example 2: Traffic Light System

signal = "yellow" 

if signal == "red": 
    print("Stop") 
elif signal == "yellow": 
    print("Get Ready") 
elif signal == "green": 
    print("Go") 
            

Output

Get Ready
            

Explanation

Since the signal is "yellow", the corresponding elif block executes.

Example 3: Age Category

age = 20 

if age < 13: 
    print("Child") 
elif age < 20: 
    print("Teenager") 
elif age < 60: 
    print("Adult") 
            

Output

Adult
            

Explanation

The age is 20, so the third condition (age < 60) becomes True.

Common Mistakes

❌ Wrong:

elif age > 18: 
    print("Adult")
            

(elif cannot be used without a preceding if.)

✅ Correct:

if age < 18: 
   print("Minor") 
elif age >= 18: 
   print("Adult")
            

The elif statement helps handle multiple conditions efficiently. It makes code more readable and avoids writing multiple separate if statements.