The elif
statement in Python allows you to check multiple conditions and selectively execute code based on the first condition that evaluates to True
. Known as the “else if” statement, it provides an efficient way to make decisions in your code based on multiple possibilities.
In this comprehensive guide, we will cover the syntax, use cases, and examples of the elif
statement in Python. You will learn how to leverage elif
to handle complex conditional logic, write cleaner code, and improve flow control in your Python programs.
Table of Contents
Open Table of Contents
Introduction to the elif Statement
The elif
statement in Python is used to check for multiple conditions in sequential order. It always follows an initial if
statement and precedes the final else
statement in an if-elif-else
block.
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
statement4
The elif
statements allow you to essentially say “if not… then try this next condition”. If the initial if
condition is False
, then the first elif
condition is checked. If that evaluates to False
, then the next elif
is checked, and so on until an elif
condition equates to True
or the else
block is reached.
The key advantages of using elif
include:
- Checking for multiple conditions instead of nested
if
statements or long conditional expressions. - Improved readability and modularized conditional checking.
- Avoiding duplication since you can execute different code for each condition.
- Ability to add extra conditions later without restructuring your code.
Now let’s look at some common use cases for the elif
statement in Python.
Use Cases for the elif Statement
1. Evaluating Multiple Discrete Conditions
One of the most common uses of elif
is to check for multiple distinct conditions and execute different code blocks based on which one is true.
For example:
age = 30
if age < 18:
print("Minor")
elif age >= 18 and age < 65:
print("Adult")
else:
print("Senior")
Here elif
allows us to test for two additional age ranges beyond the initial if
condition.
2. Multi-way Branching
The elif
statement excels at multi-way branching - making a decision based on multiple possible exclusive outcomes. Each elif
checks for a different condition, with optional final else
to catch anything else.
For example:
day = "Tuesday"
if day == "Monday":
print("It's Monday!")
elif day == "Tuesday":
print("It's Tuesday!")
elif day == "Wednesday":
print("It's Wednesday!")
else:
print("It's some other day!")
This tests for 3 possible day values before defaulting to the else
statement.
3. Validating User Input
Another very common use of elif
is to validate user input by checking if it matches expected formats or values.
For example:
user_input = input("Enter 'y' or 'n': ")
if user_input == 'y':
print("You entered yes")
elif user_input == 'n':
print("You entered no")
else:
print("Invalid input")
Here elif
allows us to verify two valid options for input before rejecting everything else.
4. Error and Exception Handling
The elif
statement can also be leveraged for error and exception handling in Python. Each elif
can check for a different type of error or exception that may occur in a try/except block.
For example:
try:
# Code that may throw an error
pass
except ValueError:
print("Caught ValueError")
elif KeyError:
print("Caught KeyError")
elif EOFError:
print("Caught EOFError")
else:
print("No exceptions caught")
This tests for 3 different exceptions and executes custom handling code for each one.
elif Statement Syntax and Rules
Now that we’ve seen common use cases, let’s go over the proper syntax and rules for elif
statements in Python:
elif
always follows anif
statement and precedes an optionalelse
statement.- There can be zero to many
elif
branches after the initialif
. - Only the code under the first
if/elif
condition that equates toTrue
will be executed. The rest are skipped. - The
else
block is executed only when allif
andelif
conditions areFalse
. elif
conditions must be Boolean expressions that evaluate toTrue
orFalse
.- The syntax is
elif expression:
with the condition followed by a colon. - Indentation follows the same rules as other Python block statements.
Let’s look at an example with all these components:
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
statement4
Following proper indentation and syntax is crucial when working with elif
statements in your code.
Comparing elif and Else If
In Python, elif
and else if
work identically when testing multiple conditions. For example:
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
Is equivalent to:
if x > 0:
print("Positive")
else:
if x < 0:
print("Negative")
else:
print("Zero")
However, many Python programmers prefer using elif
statements because they are:
- More concise and take up less lines of code.
- Avoid nesting and improve readability.
- Offer a visual distinction for multiple condition checking.
So in general, use elif
when checking multiple mutually exclusive conditions to improve your code’s organization and readability.
Elif Statement Examples and Patterns
Now let’s look at some examples of elif
statements in action across a variety of use cases.
Basic Conditional
This basic example prints a message based on the value of a number:
num = 5
if num > 0:
print(f"{num} is positive")
elif num < 0:
print(f"{num} is negative")
else:
print(f"{num} is zero")
Grade Calculator
Here elif
allows us to check a grade percentage against multiple letter grade thresholds:
grade_percent = 84
if grade_percent >= 90:
letter_grade = "A"
elif grade_percent >= 80:
letter_grade = "B"
elif grade_percent >= 70:
letter_grade = "C"
elif grade_percent >= 60:
letter_grade = "D"
else:
letter_grade = "F"
print(letter_grade)
Handling Different Errors
This example shows handling different exception types in the except blocks:
try:
# Code that may throw an error
except ValueError:
print("Caught ValueError")
elif TypeError:
print("Caught TypeError")
elif ZeroDivisionError:
print("Caught ZeroDivisionError")
else:
print("No exceptions caught")
User Input Validation
In this example we validate two different user inputs using elif
:
user_num = input("Enter a number: ")
user_choice = input("Select an option (A/B): ")
if not user_num.isdigit():
print("Invalid number entered")
elif user_choice not in ["A", "B"]:
print("Invalid option selected")
else:
# Further code to process valid input
pass
Nested Elif Statements
While you want to avoid over-nesting if statements, sometimes a nested elif
can improve the conditional logic:
num = 15
if num > 0:
if num % 2 == 0:
print(f"{num} is positive and even")
elif num % 2 != 0:
print(f"{num} is positive and odd")
elif num < 0:
print(f"{num} is negative")
Multi-way Branching
This code uses a chain of elif
statements to print a message based on the day of the week:
day = "Monday"
if day == "Monday":
print("Today is Monday")
elif day == "Tuesday":
print("Today is Tuesday")
elif day == "Wednesday":
print("Today is Wednesday")
elif day == "Thursday":
print("Today is Thursday")
elif day == "Friday":
print("Today is Friday")
elif day == "Saturday":
print("Today is Saturday")
else:
print("Today is Sunday")
These examples demonstrate some of the flexible ways you can leverage elif
statements for conditional testing and branching logic in your Python code.
Best Practices for Elif Statements
When using elif
statements, keep these best practices in mind:
- Favor simplicity - Avoid long chains of
elif
blocks when possible. Refactor into functions. - Indent properly - Maintain correct indentations for the
if
,elif
,else
blocks per Python style standards. - Comment well - Use comments to document what each code block under the conditions is doing.
- Check most likely first - Order
elif
conditions from most to least probable to optimize performance. - Cover all cases - Include an
else
catch-all condition or exceptions handling for unanticipated cases. - Avoid repeats - Refactor similar handling code into functions or methods to avoid duplication.
- Limit nesting - Deeply nested
if/elif
statements can be difficult to read. Try to limit nesting.
Adhering to these best practices will help ensure your elif
statements are written efficiently and are easy to maintain.
Common Mistakes to Avoid
As you start integrating more elif
statements, watch out for these common mistakes:
- Forgetting the colon
(:)
after eachelif
condition. - Indenting
elif
blocks incorrectly, rather than aligning with theif
statement. - Checking for mutually inclusive conditions rather than mutually exclusive.
- Not covering all possible cases in complex conditionals.
- Repeating handling code across
elif
blocks rather than refactoring.
Carefully proofreading your elif
conditionals and running tests can help you catch these kinds of errors early.
Conclusion
The elif
statement in Python provides an efficient and readable way to check multiple conditions. Key takeaways include:
- Use
elif
when you need to make a decision based on multiple exclusive options. elif
allows you to test each condition sequentially and execute different code blocks.- It improves readability over nested
if
statements or complexor
/and
logic. - Proper syntax, indentation, and order matters when using
elif
. - leverage
elif
for input validation, error handling, branching, and more.
Learning how to effectively use elif
for conditional testing is a key skill for Python programmers. This guide should provide a comprehensive overview of how and when to use elif
statements in your own code.
Happy Python programming!