Course contentsShow
← Python
Lesson 16 of 1,0601. Foundations and EnvironmentFree lesson

Managing Program Flow with Else and Elif

You will learn how to handle multiple conditional scenarios by chaining alternative pathways to your primary if statements.

Managing Program Flow with Else and Elif

In this lesson, you will learn how to build more complex decision-making logic by adding "fallback" and "alternative" pathways to your if statements.

Moving Beyond Simple If Statements

So far, you have used if statements to check if a condition is true. But what happens if that condition is false? Sometimes, you want your program to do something completely different instead of just moving on to the next line of code.

The Else Statement

The else keyword acts as a catch-all. If your if condition evaluates to False, the code inside the else block will run automatically. Think of it as your program’s "Plan B."

age = 15

if age >= 18:
    print("You are an adult.")
else:
    print("You are still a minor.")

The Elif Statement

What if you have more than two outcomes? Perhaps you want to check for multiple specific scenarios. This is where elif (short for "else if") comes in. You can chain as many elif statements as you need after an initial if to check multiple conditions in order. Python will stop as soon as it finds the first condition that is true.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

In this example, if the score is 85, the first check (>= 90) is False. The program moves to the first elif, which is True, so it prints "Grade: B" and skips the rest of the chain. If none of the conditions are met, the final else block executes as a default.

Using these tools, you can guide your program through sophisticated logic paths, ensuring that every possible user input or variable state is handled gracefully.

Key Takeaway: Use elif to check multiple specific conditions in sequence, and use else to define a default behavior when none of the previous conditions are met.