Course contentsShow
← Python
Lesson 75 of 1,0602. Control Flow and LogicFree lesson

Evaluating Multiple Conditions with Elif Chains

Use the elif statement to check a series of sequential conditions and execute the first block that evaluates to True.

Evaluating Multiple Conditions with Elif Chains

In this lesson, you will learn how to check a long list of specific, sequential possibilities using elif chains to keep your code organized.

Beyond the Binary Choice

So far, you’ve used if and else to create a simple fork in the road. if handles one case, and else handles everything else. But what if you have three, four, or ten different paths to choose from? If you tried to nest if statements inside each other, your code would quickly become messy and hard to read.

This is where elif (short for "else if") comes in. An elif chain allows you to check multiple conditions one after another. Python evaluates these from top to bottom. It executes the block of the first condition that evaluates to True and then skips the rest of the chain entirely.

Example: Grading a Score

Imagine you are assigning a letter grade based on a numeric score. An elif chain allows you to check these ranges cleanly:

score = 85

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

In this example, Python checks the conditions in order:

  1. Is the score 90 or higher? No.
  2. Is the score 80 or higher? Yes!
  3. Because the second condition is met, it executes print("Grade: B") and ignores the remaining elif and else blocks.

Why Use Elif Chains?

The beauty of this structure is that it acts as a "priority list." By placing your most specific conditions at the top, you ensure that Python catches the first match it finds. The final else acts as a safety net, catching any cases that didn't fit into the categories defined by your if and elif statements. This approach makes your logic easy to read, follow, and maintain.

Key Takeaway: An elif chain evaluates conditions in order and executes only the first block that results in True, providing a clean way to handle multiple mutually exclusive options.