Blog Post #27: Handling Multiple Scenarios with elif

In Post #26, we mastered the if-else statement, which is perfect for handling two possible outcomes—a clear “this or that” decision. But what happens when the world isn’t so black and white? What if we need to choose between three, four, or even more possible paths?

For example, how would we write a program to determine if a number is positive, negative, or zero? An if-else block can only handle two of those cases. To solve this, Python gives us the elif keyword. In this post, you’ll learn how to build complex decision-making chains to handle any number of scenarios.

Chaining Conditions with elif

The keyword elif is short for “else if.” It lets you add another question into your if statement chain. You can use as many elif statements as you need, allowing you to create a “ladder” of checks.

Here is the crucial logic of an if-elif-else chain:

  1. Python starts at the top and checks the if condition.
  2. If it’s True, Python executes that block of code and then skips the rest of the entire chain.
  3. If the if condition is False, it moves down to the first elif and checks its condition.
  4. If that elif condition is True, it executes that block and skips the rest of the chain.
  5. It continues this process until it either finds a condition that is True or it reaches the final else block (which runs if nothing else was True).

Only one block in the entire chain will ever be executed.

The if-elif-else Syntax

The structure is a logical extension of what we already know.

if first_condition:
    # Code to run if first_condition is True
elif second_condition:
    # Code to run if first_condition is False AND second_condition is True
elif third_condition:
    # Code to run if both above are False AND third_condition is True
else:
    # Code to run if ALL preceding conditions are False

The final else block is optional. It acts as a “catch-all” or default case when none of the specific conditions you’re checking for are met.

elif in Action

Let’s look at some examples where this structure is essential.

Example 1: Number Guessing Hints

Imagine a simple number guessing game. We need to tell the user if their guess is too low, too high, or exactly right. This is a perfect three-path problem.

secret_number = 75
guess = 50

if guess < secret_number:
    print("Your guess is too low!")
elif guess > secret_number:
    print("Your guess is too high!")
else:
    print("You guessed it! The number is 75.")

If you change guess to 100, the first condition (100 < 75) is False, so Python checks the next one. The elif condition (100 > 75) is True, so it prints “Your guess is too high!” and the chain ends. If you change guess to 75, both the if and elif conditions are False, so the final else block is executed.

Example 2: Assigning Grades

This structure is also ideal for checking ranges, like assigning a letter grade based on a test score.

score = 85
grade = ""

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"The score of {score} gets a grade of: {grade}")

The order of the elif statements is very important here. With a score of 85, Python first checks if score >= 90. This is False. It then moves to the next check, elif score >= 80. This is True! Python executes grade = "B" and then completely skips the rest of the checks for C, D, and F.

What’s Next?

You are no longer limited to two-path decisions. The if-elif-else chain is a powerful tool that allows you to build complex decision trees to handle a wide variety of scenarios cleanly and efficiently.

We’ve now learned all the basic components of conditional logic. It’s time to put it all together in a practical mini-project. In Post #28, we will use our new if-elif-else skills to build a simple age-based access program.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment