Python Conditional Branching: Multiple Conditions with if, elif, and else

When creating a program, you often need branching logic like “If A, execute Process 1; otherwise, if B, execute Process 2; otherwise, execute Process 3.”

In Python, you can handle such complex conditional branches by combining if statements with elif (short for else if) and else. This article explains how to write conditional expressions with three or more branches and the important rules regarding the order of evaluation.


目次

Basic Syntax

The basic structure for checking multiple conditions is as follows:

if condition_A:
    # Process executed if condition_A is True
elif condition_B:
    # Process executed if condition_A is False AND condition_B is True
elif condition_C:
    # Process executed if A and B are False AND condition_C is True
else:
    # Process executed if ALL conditions are False
  • elif: Means “else if”. You can write as many as needed.
  • else: Means “if none of the above apply”. You can write only one at the end (it can also be omitted).

Specific Usage Examples

1. Judgment by Numeric Range (Grade Evaluation)

This is an example of changing the process based on which range a number falls into. Here, we output a grade based on an exam score.

score = 78

print(f"Score: {score}")

if score >= 90:
    print("Grade: S (Excellent)")
elif score >= 80:
    print("Grade: A (Very Good)")
elif score >= 70:
    print("Grade: B (Good)")
elif score >= 60:
    print("Grade: C (Average)")
else:
    print("Grade: D (Failure)")

Output:

Score: 78
Grade: B (Good)

This program checks conditions in order from the top:

  1. 78 >= 90 is False, so move to the next.
  2. 78 >= 80 is False, so move to the next.
  3. 78 >= 70 is True, so it outputs “Grade: B” and ends the entire process. The subsequent elif and else blocks are ignored.

2. Judgment by String Matching (Traffic Light Action)

You can branch based on the state of a string, not just numbers.

traffic_light = "yellow"

if traffic_light == "green":
    print("Proceed.")
elif traffic_light == "yellow":
    print("Stop. (Unless you cannot stop safely)")
elif traffic_light == "red":
    print("Stop.")
else:
    print("Signal error.")

Output:

Stop. (Unless you cannot stop safely)

Importance of Evaluation Order

The most important point in the if ... elif structure is that “conditions are evaluated in order from the top, and only the block that becomes True first is executed.” If you mistake the order of conditions, you may get unintended results.

Bad Example

For example, when determining membership rank, what happens if you check the easier condition “Gold Member (purchase over 50,000)” before the stricter condition “Platinum Member (purchase over 100,000)”?

total_purchase = 150000 # Purchased 150,000

# Bad Example: Improper order of conditions
if total_purchase >= 50000: # Over 50,000
    print("You are a Gold Member.")
elif total_purchase >= 100000: # Over 100,000
    print("You are a Platinum Member.")
else:
    print("You are a Standard Member.")

Output:

You are a Gold Member.

Originally, this should be judged as “Platinum Member,” but since the first condition total_purchase >= 50000 became True, the process finished there.

Correct Example

When judging ranges, you must write the stricter conditions (narrower ranges) first.

# Good Example: Write conditions in descending order of strictness
if total_purchase >= 100000: # Check over 100,000 first
    print("You are a Platinum Member.")
elif total_purchase >= 50000:
    print("You are a Gold Member.")
else:
    print("You are a Standard Member.")

Output:

You are a Platinum Member.

Summary

  • Use if, elif, and else for three or more branches.
  • You can add as many elif blocks as you like, and write else only once at the end (optional).
  • Conditions are evaluated from the top, and once a condition becomes True, subsequent conditions are ignored.
  • Be careful with the order of conditional expressions (especially numeric range checks).
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次