Skip to main content

Checking Multiple Conditions (elif)

Sometimes you have more than two choices. For example, if you want to assign a grade to a student based on their marks:

  • Marks 90 or above → Grade A
  • Marks 75 or above → Grade B
  • Marks 50 or above → Grade C
  • Anything below 50 → Grade F (Fail)

To check multiple conditions one after the other, Python uses elif (which is short for "else if").


1. Syntax Structure: Anatomy of an elif Chain

Python evaluates conditions top to bottom. The moment it finds a condition that is True, it runs that block of code and skips the remaining checks!

Syntax Structure of an if-elif-else Chain

ifcondition_A:
INDENTATION(4 Spaces)
IF BLOCK 1Executes if condition_A is True
elifcondition_B:
INDENTATION(4 Spaces)
ELIF BLOCK 2Executes if condition_B is True
elifcondition_C:
INDENTATION(4 Spaces)
ELIF BLOCK 3Executes if condition_C is True
else:
INDENTATION(4 Spaces)
ELSE BLOCKExecutes if ALL previous conditions are False

2. The if-elif-else Code Example

marks = 82

if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F (Fail)")

# Output: Grade: B

⚠️ Golden Rule: The Order Matters!

Always place your checks starting with the most restrictive or highest value at the top.

If we wrote if marks >= 50: at the very top, a student with 95 marks would trigger that first condition and get a "Grade C" immediately, and Python would skip the rest of the checks!


3. Real-Time Example: Signal Traffic Light

signal = "yellow"

if signal == "red":
print("STOP immediately!")
elif signal == "yellow":
print("Prepare to stop or proceed with caution.")
elif signal == "green":
print("GO!")
else:
print("Invalid signal color.")

Quick Summary

  • elif (Else If): Evaluates alternative conditions sequentially when the initial if is False.
  • First True Match: Only the first condition that evaluates to True runs; subsequent elif blocks are ignored.
  • Catch-All else: An optional fallback at the very end when none of the conditions match.

What's Next?

When making decisions inside decisions, check out the next lesson: Nested Conditions!