Concepts / else-if (elif) Statements

else-if (elif) Statements

The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block ), else we process another block of statements (called the else-block ). The else clause is optional.

  • Programming

Why Multiple Conditions Matter

When you write a program that makes decisions, you often face more than two choices. For example, a guessing game might need to tell a player whether their guess is too low, too high, or exactly right. With only if and else, you would need to nest one decision inside another, creating deeply indented code that becomes hard to read. The elif statement solves this by letting you chain multiple conditions in a flat, linear way. Only one block executes, and the program stops checking conditions as soon as it finds one that is true.

What elif Actually Does

elif is short for else-if. It combines an else clause with a new if condition into a single statement. When the first if condition is false, the program checks the elif condition. If that is also false, it can check another elif, and so on. Finally, an optional else clause catches any case where none of the conditions above it were true. The key insight is that elif and else are optional—you can have an if statement all by itself—but once a condition is true and its block executes, the entire if-elif-else chain stops, and no other blocks in that chain will run.

In an if-elif-else chain, exactly one block executes, never zero and never more than one. The program evaluates conditions from top to bottom and stops as soon as it finds a true condition.

How Conditions Are Checked

To understand elif, it helps to trace through a concrete example step by step. Imagine a program that reads a number representing a test score and prints feedback. The program checks: Is the score 90 or higher? If not, is it 80 or higher? If not, is it 70 or higher? If none of those are true, the score is below 70.

truefalsetruefalsetruefalsescore = 85score >= 90?Print 'A'Continuescore >= 80?Print 'B'score >= 70?Print 'C'Print 'F'
When does the program check each condition, and which block actually runs? Follow the arrows to see how the program stops as soon as it finds a true condition.

In this flowchart, when score is 85, the program first checks if score >= 90. That is false, so it moves to the elif and checks if score >= 80. That is true, so it prints 'B' and then exits the entire chain. It never checks the remaining elif or the else block. This is the crucial behavior: once a condition is true, the program executes that block and skips all the rest.

Syntax and Structure

An if-elif-else statement has a specific structure. The if keyword starts the chain and must be followed by a condition and a colon. The elif keyword introduces an alternative condition, also followed by a colon. The else keyword (if present) has no condition, only a colon. Each block of code must be indented consistently beneath its keyword. Multiple elif clauses can appear in sequence, and the else clause is always optional.

Both elif and else must end with a colon, and the statements in their blocks must be indented. A minimal valid if statement requires only the if keyword, condition, colon, and indented block—elif and else are optional.

python

Worked Example: Guessing Game Feedback

Comparing a Guess to a Secret Number

Write an if-elif-else chain that compares a player's guess to a secret number (42) and tells them whether their guess is too low, too high, or correct.

Set up the variables: We have a secret number (42) and a guess from the player. We need to compare them.

Check if the guess is correct: The first if condition checks if guess == 42. If true, we tell the player they won. This is the most specific condition, so it goes first.

Check if the guess is too low: If the guess is not correct, the first elif checks if guess < 42. If true, we tell the player to guess higher.

Handle the remaining case: If the guess is not correct and not too low, it must be too high. The else block handles this without needing another condition.

The program prints exactly one message based on the relationship between the guess and the secret number. Once a condition is true, no other blocks execute.

python
Output (expected)
Your guess is too low. Try a higher number.

In this example, guess is 35 and secret is 42. The program checks the first condition: is 35 == 42? No, so it moves to the elif. Is 35 < 42? Yes, so it prints the message about guessing too low and then exits the chain. The else block never runs because a condition was already true.

Order Matters in elif Chains

The order of your conditions in an if-elif-else chain affects which block runs. Because the program stops as soon as it finds a true condition, you should arrange your conditions from most specific to most general. If you put a general condition first, it might catch cases you intended for a more specific condition later, and that later condition will never be reached.

yesnoyesnono (else)Check condition 1Check condition 2Check condition 3Condition 1 true?Condition 2 true?Condition 3 true?Execute block 1Execute block 2Execute else blockExit chainExit chainExit chain
Does the program check all conditions or stop after finding the first true one? Trace the order of checks and see where the program exits.

Imagine a discount system for an online store. You might offer a 50% discount for orders over 500 dollars, a 20% discount for orders over 100 dollars, and a 5% discount for orders over 50 dollars. If you check the 5% condition first, every order over 50 dollars gets 5%, and the larger discounts are never reached. By checking from largest to smallest (500, then 100, then 50), you ensure each order gets the best possible discount.

Common Mistakes

  • Forgetting the colon after elif or else

    Python requires a colon at the end of every if, elif, and else line. Without it, the code will not run and you will get a syntax error.

    Fix: elif score >= 80: print('B')

  • Incorrect indentation in elif or else blocks

    Python uses indentation to define which statements belong to each block. If the statements are not indented, Python thinks they are outside the if-elif-else chain.

    Fix: if x > 0: print('positive') elif x < 0: print('negative')

  • Putting a condition after else

    The else keyword does not take a condition. It catches all remaining cases. If you need to check another condition, use elif instead.

    Fix: if age >= 18: print('Adult') else: print('Minor')

  • Checking overlapping conditions in the wrong order

    A score of 95 will match the first condition (>= 70) and print 'Pass', so the second condition (>= 90) is never checked. The more specific condition should come first.

    Fix: if score >= 90: print('Excellent') elif score >= 70: print('Pass')

  • Using multiple if statements instead of elif

    Each if is independent, so a score of 95 will print 'A', 'B', and 'C' all at once. With elif, only one block runs.

    Fix: if score >= 90: print('A') elif score >= 80: print('B') elif score >= 70: print('C')

When to Use elif vs. Nested if

Before elif existed, programmers had to nest if statements inside else blocks to handle multiple conditions. This created deep indentation and was hard to read. The elif statement flattens this structure. When you have a series of mutually exclusive conditions (only one can be true), use if-elif-else. When you have independent conditions that might all be true, use separate if statements.

python

In the first example, a temperature cannot be both hot and warm at the same time, so elif is appropriate. In the second example, a patient can have multiple conditions simultaneously, so separate if statements are correct. Using elif when you need independent checks would hide important information from the user.

Practice: Categorizing User Input

MEDIUM

Write an if-elif-else chain that reads a number from a user and prints a category: 'Even' if the number is divisible by 2, 'Divisible by 3' if it is divisible by 3 (but not 2), and 'Other' otherwise. What order should you check the conditions in, and why?

Hints
  • Use the modulo operator (%) to check if a number is divisible by another.
  • Think about whether a number can be both even and divisible by 3 at the same time.
  • Remember that elif stops checking once a condition is true.

Summary

You now understand how elif extends the if-else structure to handle multiple conditions in a clean, readable way. The key points are: elif stands for else-if and lets you chain conditions; only one block in an if-elif-else chain executes, and the program stops checking as soon as it finds a true condition; both elif and else require a colon and proper indentation; and you should order conditions from most specific to most general to avoid masking later conditions. Use elif for mutually exclusive cases and separate if statements for independent conditions.

Key Takeaways

  • elif (else-if) lets you chain multiple conditions in a single if-elif-else structure, avoiding deep nesting and improving readability.
  • Only one block executes in an if-elif-else chain; the program checks conditions from top to bottom and stops as soon as it finds one that is true.
  • Both elif and else must end with a colon, and their code blocks must be indented consistently.
  • Order your conditions from most specific to most general to ensure each case is handled correctly and later conditions are not masked.
  • Use elif for mutually exclusive conditions and separate if statements for independent conditions that might all be true.