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. The if-elif-else Chain

Python checks each condition from top to bottom. The moment it finds a condition that is True, it runs that block of code and ignores all other options below it.

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!


2. Nested Conditions (Choices Inside Choices)

Sometimes, you need to check a condition only after another condition has passed. This is called nesting (putting one if-else statement inside another one).

Real-Time Example: Blood Donation Eligibility

To donate blood, you must meet two rules:

  1. You must be 18 years or older.
  2. If you are old enough, you must weigh 50 kg or more.

Let's see how this works in Python:

age = 20
weight = 55

# Outer Check: Age
if age >= 18:
print("Age check passed.")

# Inner (Nested) Check: Weight
if weight >= 50:
print("You are eligible to donate blood!")
else:
print("Sorry, you must weigh 50 kg or more to donate.")

else:
print("Sorry, you must be 18 or older to donate blood.")

Note on Nesting:

Notice the indentation! The inner if-else block is pushed even further to the right (8 spaces) because it belongs inside the outer if statement block. While nesting is very useful, try to keep it simple - deep nesting can make your code hard to read!


What's Next?

If you have many exact options to match, writing multiple elif blocks can become tedious. Let's learn about Python's modern match-case statement and try some exercises in the next lesson!