Course contentsShow
← Python
Lesson 74 of 1,0602. Control Flow and LogicFree lesson

Providing Alternative Paths with Else Statements

Implement the else statement to define a fallback code block that executes when the initial if condition evaluates to False.

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

  1. Always indent: The code inside the else block must be indented, just like the code inside the if block.
  2. Pairs only: An else statement cannot exist on its own; it must be attached to an if statement.
  3. Exclusivity: Python will execute either the if block or the else block, 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.