Python elif Statement

Python elif Statement

The elif (short for else if) keyword is used when you want to check multiple conditions after an initial if condition. It lets your program choose between more than two options.

Syntax:

if condition1:
   # Block of code if condition1 is True
elif condition2:
   # Block of code if condition2 is True
elif condition3:
   # Block of code if condition3 is True
else:
   # Block of code if all above conditions are False

Only the first condition that evaluates to True will execute. All remaining conditions are skipped.

Example 1: Grading System

marks = 85
if marks >= 90:
   print("Grade: A")
elif marks >= 80:
   print("Grade: B")
elif marks >= 70:
   print("Grade: C")
else:
   print("Grade: F")

Output:

Grade: B

Example 2: Temperature Check

temperature = 35
if temperature > 40:
   print("It's extremely hot!")
elif temperature > 30:
   print("It's hot.")
elif temperature > 20:
   print("It's warm.")
else:
   print("It's cold.")

Output:

It's hot.

Example 3: Day of the Week

day = 3
if day == 1:
   print("Monday")
elif day == 2:
   print("Tuesday")
elif day == 3:
   print("Wednesday")
elif day == 4:
   print("Thursday")
else:
   print("Another day")

Output:

Wednesday

Key Points

  • elif is optional and can be used multiple times.
  • Only the first matching condition block is executed.
  • Use else at the end for a default/fallback case (optional).

Practice Exercise

Write a program to categorize an integer as positive, negative, or zero.

num = 0
if num > 0:
   print("Positive number")
elif num < 0:
   print("Negative number")
else:
   print("Zero")

Output:

Zero