Providing Alternative Paths with Else Statements
In this lesson, you will learn how to provide a "backup plan" for your programs using the else statement.
The Logic of the Else Statement
So far, you’ve used if statements to execute code only when a specific condition is True. But what happens if that condition is False? Usually, Python simply skips the if block and moves on. If you want your program to perform a specific action specifically when the condition fails, you use the else statement.
Think of it like a fork in the road:
- If the light is green, you drive.
- Else (if it's not green), you stop.
The else statement acts as a catch-all that triggers whenever the preceding if condition evaluates to False.
Putting it into Code
Here is how you structure this in Python:
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not old enough to vote yet.")
In this example, if the user enters 20, the if condition is True, so the first message prints. If the user enters 15, the condition is False. Instead of the program doing nothing, the else block catches that False result and prints the second message.
Important Rules to Remember
- Always indent: The code inside the
elseblock must be indented, just like the code inside theifblock. - Pairs only: An
elsestatement cannot exist on its own; it must be attached to anifstatement. - Exclusivity: Python will execute either the
ifblock or theelseblock, but never both. It is a mutually exclusive path.
By using else, you ensure that your program provides clear feedback regardless of the input, making your logic robust and user-friendly.
Key Takeaway: The else statement provides a fallback path that executes only when the if condition evaluates to False.