What is the "elif" statement in Python and how to use it?
Table of Contants
Introduction:
The elif statement in Python stands for "else if" and is used to add multiple conditions to an if-else structure. It allows your program to evaluate a sequence of conditions, executing the first block of code where the condition is True. If none of the if or elif conditions are True, the else block (if present) is executed. The elif statement helps you handle complex logic with multiple decision points in a clean and readable way.
Syntax and Basic Usage of the elif Statement
The structure of an if-elif-else block looks like this:
if: Checks the first condition.elif: Checks another condition if the previousif(orelif) condition isFalse.else: A final block that runs if none of the conditions areTrue.
Example:
- In this example, if
ageis less than 18, the program prints "You are a minor." If it's between 18 and 64, it prints "You are an adult." Otherwise, it prints "You are a senior citizen."
How the elif Statement Works
- The
ifcondition is evaluated first. - If the
ifcondition isTrue, the corresponding block of code is executed, and the rest of theelifandelseblocks are skipped. - If the
ifcondition isFalse, the program evaluates the firstelifcondition. - This process continues for each
elifcondition until aTruecondition is found or all conditions have been evaluated. - If none of the conditions are
True, theelseblock is executed.
Example: Multiple Conditions Using elif
- Here, the program checks each condition in sequence. Since
scoreis 75, the conditionscore >= 70isTrue, so it prints "Grade: C" and skips the rest of the conditions.
When to Use elif
You should use elif when you need to check multiple conditions and want to avoid nested if statements, which can make your code less readable. The elif structure is a cleaner and more efficient way to handle multiple decision points.
Example: Checking Multiple Categories
- In this example, the program evaluates each condition. Since
temperatureis 30, the output is "It's warm."
Combining elif with Logical Operators
You can also combine conditions in the elif block using logical operators like and, or, and not to create more complex conditions.
Example:
- In this example, multiple conditions are combined using the
andoperator in theelifblock to differentiate between morning and afternoon on Sunday.
Practical Examples of Using elif
1. Using elif in Age Verification:
2. Handling Multiple Conditions with elif:
3. Grading System Using elif:
Conclusion:
The elif statement in Python is a versatile tool for handling multiple conditions in your programs. It works seamlessly with if and else to create efficient, readable decision-making structures. By using elif, you can avoid deeply nested if statements and write clean, easy-to-understand code. Whether you are building complex decision trees or handling simple conditional logic, the elif statement provides a powerful way to control the flow of your program.