Introduction

The if elif else statement in Python is essential for decision-making in your programs. The statement allows you to execute specific blocks of code based on conditions. You can use this structure to handle complex logic effectively. With its flexible design, you can create dynamic programs that adapt to user inputs and data. The if elif else statement allows you to implement multiple decision paths and logical flows.

This guide shows you how to use the Python if elif else statement.

Prerequisites

Before you begin:

  • Deploy A VPS server. For instance, Ubuntu 24.04.
  • Create a non-root sudo user.
  • Install Python.

Declare Python if elif else Statement

The if elif else statement evaluates one or more conditions. If a condition returns True, the code block beneath it runs. If no conditions are True, the else block executes. Here is the syntax:

Python
if condition1:
    # code block for condition1
elif condition2:
    # code block for condition2
else:
    # code block if no conditions are true

Here's an example:

Python
temperature = 30

if temperature > 35:
    print("It's extremely hot.")
elif temperature > 25:
    print("It's warm.")
else:
    print("It's cool.")

This code prints It's warm. because the temperature is 30.

Combine Multiple Conditions

You can combine conditions using logical operators such as and, or, and not:

  • and: All conditions must be True.
  • or: At least one condition must be True.
  • not: Reverses the logical state of a condition.

For example:

Python
age = 20
has_license = True

if age >= 18 and has_license:
    print("You can drive.")
elif age < 18 or not has_license:
    print("You cannot drive.")
else:
    print("Invalid input.")

In this case, Python prints You can drive. because both conditions evaluate to True.

Logical operators make your conditions more flexible, allowing you to handle complex situations easily.

Use Nested if elif else Statements

Nested if elif else statements let you check conditions within other conditions. This structure is helpful for multi-level decision-making.

For instance:

Python
marks = 85

if marks >= 50:
    if marks >= 75:
        print("You passed with distinction.")
    else:
        print("You passed.")
else:
    print("You failed.")

Here, the program first checks if marks are above 50. If True, the program then checks if marks are above 75. The program outputs the You passed with distinction. message because 85 satisfies both conditions.

Use nested statements carefully to avoid overly complicated code.

Implement Python if elif else Statement Best Practices

Follow these best practices to write clean, efficient, and maintainable code:

  • Use meaningful variable names: Clear names help others understand your conditions.
  • Avoid deep nesting: Simplify nested statements to enhance readability.
  • Combine conditions: Use logical operators where possible to reduce the number of checks.
  • Test all scenarios: Ensure every condition and edge case is handled.
  • Keep blocks concise: Limit each block to a few lines for clarity.

Example:

Python
score = 92

if score > 90:
    print("Excellent performance.")
elif 70 <= score <= 90:
    print("Good performance.")
else:
    print("Needs improvement.")

In this example, the logical operator keeps the elif condition compact and easy to read.

Discover if elif else Statement Practical Use Cases

Practical use cases for if elif else statements include:

  • Form Validation: Ensure user inputs meet specific criteria.
  • Gaming Logic: Handle player decisions and outcomes.
  • Data Analysis: Categorize data based on thresholds.
  • IoT Programming: Make decisions based on sensor readings.
  • Customer Segmentation: Group customers by age, location, or preferences.

Example in a real-world application:

Python
age = 25

if age < 13:
    category = "Child"
elif 13 <= age < 18:
    category = "Teenager"
else:
    category = "Adult"

print(f"Category: {category}")

The above example shows how to categorize users based on age.

Conclusion

The if elif else statement is a cornerstone of decision-making in Python. The statement lets you create dynamic, responsive programs by evaluating multiple conditions. You've learned how to declare these statements, combined conditions, handled nested logic, followed best practices, and explored practical use cases. Mastering the if elif else concept is essential for writing efficient and maintainable Python code.