Python elif statement

The elif statement in Python is a conditional branching tool that allows you to check multiple conditions sequentially. It stands for “else if” and is used as part of an if-elif-else structure to test multiple conditions, executing the first block where the condition evaluates to True. This simplifies decision-making in code and avoids nested if statements.

Example

score = 85

if score >= 90:

    print("Grade: A")

elif score >= 80:

    print("Grade: B")

elif score >= 70:

    print("Grade: C")

else:

    print("Grade: F")

Output:

Grade: B

elif Syntax

if condition1:

    # Block of code for condition1

elif condition2:

    # Block of code for condition2

elif condition3:

    # Block of code for condition3

else:

    # Block of code if no conditions are True
  • condition: An expression that evaluates to True or False.
  • else: Optional block that executes if none of the preceding conditions are True.

Why Use elif?

The elif statement is ideal for simplifying code that involves multiple conditional checks. Instead of deeply nested if statements, elif allows you to write cleaner and more readable logic. It ensures only one block of code runs in an if-elif-else structure, even if multiple conditions evaluate to True. Lets see some examples:

1. Grading System

Scenario: Categorizing scores into grades based on thresholds.

score = 73

if score >= 90:

    print("Grade: A")

elif score >= 80:

    print("Grade: B")

elif score >= 70:

    print("Grade: C")

else:

    print("Grade: F")

If score is 73, the output will be:

Grade: C

2. Age Categorization

Scenario: Classifying age groups for a survey.

age = 25

if age < 18:

    print("Minor")

elif age < 65:

    print("Adult")

else:

    print("Senior Citizen")

Output:

Adult

3. Temperature Range

Scenario: Identifying temperature levels based on ranges.

temperature = 15

if temperature < 0:

    print("Freezing")

elif temperature <= 20:

    print("Cold")

elif temperature <= 30:

    print("Warm")

else:

    print("Hot")

If temperature is 15, the output will be:

Cold

Key Notes

  1. Sequential Execution: Conditions are evaluated in order. The first True condition executes, and the rest are skipped.
  2. Efficient Logic: Avoids excessive nesting, making the code easier to read and debug.
  3. Optional else: You can omit the else block if no fallback logic is needed.
  4. Flexible Conditions: Supports multiple elif statements, handling complex decision trees gracefully.

By using elif effectively, you can write concise and robust decision-making logic that is easy to understand and maintain.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top