Your code often needs to choose between more than just two options. While you could use multiple `if` statements, Python provides a much cleaner and more efficient way to handle this: the `if-elif-else` statement. It allows you to check a series of conditions and execute exactly one block of code.
🤝 The If-Else Statement: An Either/Or Choice
Let’s start with a simple choice. An `if-else` statement is perfect for situations where you need to do one thing if a condition is True, and a different thing if it is False. The else
part has no condition; its body simply runs when the if
condition is False. This guarantees that exactly one of the two blocks will execute. For example:if num == 0:
result = "The number was zero."
else:
result = "The number was not zero."
🪜 The If-Elif-Else Chain: Multiple Choices
What if you have more than two possibilities, like checking if a number is positive, negative, or zero? This is the perfect job for an `if-elif-else` statement. `elif` is short for “else if”. Python checks the `if` condition first. If it’s False, it moves to the first `elif` and checks its condition. It continues down the chain until it finds a condition that is True, executes that block, and then skips the rest of the statement. The final `else` is a catch-all that runs if none of the preceding conditions were True.
💡 Why Use Elif Instead of Multiple Ifs?
Using an `if-elif-else` structure is better than using a series of separate `if` statements for two main reasons. First, it’s more efficient because Python stops checking as soon as it finds a true condition. With separate `if` statements, it would have to check every single one. Second, it clearly shows that all the conditions are related and that only one outcome is expected, which makes your code much easier to read and understand.
Mastering the `if-elif-else` chain gives you precise control over your program’s flow, allowing you to handle any number of mutually exclusive options with clean and efficient code.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python