Complex Control Flow with 'elif' and 'else'

SA
StudyAI
AI-generated study notes
· Published Updated

From the csc241\ curriculum

TL;DR

When you need to check multiple conditions sequentially, elif allows you to test additional cases after an initial if statement. The else block acts as a catch-all, running its code if none of the preceding if or elif conditions were true. This creates a clear, efficient decision-making structure in your code.

1. The Mental Model

Imagine you're making a series of decisions, like choosing what to wear based on the weather. You first check if it's hot. If not, you check if it's raining. If neither of those is true, you wear something standard. That's exactly how if, elif, and else work together.

2. The Core Material

In programming, we often need to execute different blocks of code based on various conditions. You're already familiar with if statements for single conditions. When you have more than two possible paths, elif (short for "else if") and else become incredibly useful for creating sophisticated decision trees.

How elif Works

Close-up of hand painting floral design on paper using fine brush.
Photo by Sedanur Kunuk on Pexels

An elif statement is always paired with an if statement (and can be followed by more elifs). It only gets evaluated if the preceding if condition (and any elifs before it) was False. As soon as one if or elif condition is True, its block of code runs, and the entire if/elif/else structure is exited. This means only one block of code within the entire sequence will ever execute.

score = 85

if score >= 90:
    print("Excellent! You got an A.")
elif score >= 80: # This only runs if score was NOT >= 90
    print("Great job! You got a B.")
elif score >= 70: # This only runs if score was NOT >= 90 AND NOT >= 80
    print("Good effort! You got a C.")

The Role of else

Central red wooden figure surrounded by beige figures symbolizing leadership and individuality.
Photo by Ann H on Pexels

The else statement is optional, but it's very powerful. It acts as a default or fallback. If none of the if or elif conditions above it evaluate to True, the code within the else block will execute. You can only have one else at the very end of an if/elif sequence.

temperature = 15 # degrees Celsius

if temperature > 25:
    print("It's hot outside!")
elif temperature > 15: # Checks if temperature is > 15 AND NOT > 25
    print("It's pleasant.")
else: # This runs if temperature is NOT > 25 AND NOT > 15
    print("It's a bit chilly.")

Here's how the control flow works for an if/elif/else structure:

graph TD
    A["Start"] --> B{Condition 1 is True?};
    B -- Yes --> C["Execute Block 1"];
    B -- No --> D{Condition 2 is True?};
    D -- Yes --> E["Execute Block 2"];
    D -- No --> F{Condition 3 is True?};
    F -- Yes --> G["Execute Block 3"];
    F -- No --> H["Execute Else Block (Default)"];
    C --> Z["End"];
    E --> Z;
    G --> Z;
    H --> Z;

This diagram shows how your program makes decisions. It tries conditions one by one, top to bottom. The first one that's true gets executed, and then the program moves on past the entire structure. If none are true, the else block (if present) is the final choice.

3. Worked Example

Let's say you're writing a program for a vending machine that dispenses drinks based on a numerical code.

drink_code = 3

if drink_code == 1:
    print("Dispensing Soda...")
    cost = 1.50
elif drink_code == 2:
    print("Dispensing Water...")
    cost = 1.00
elif drink_code == 3:
    print("Dispensing Juice...")
    cost = 2.00
else:
    print("Invalid code. Please try again.")
    cost = 0.00

print(f"Your drink costs ${cost:.2f}.")

In this example, drink_code is 3.
1. if drink_code == 1: is False.
2. elif drink_code == 2: is False.
3. elif drink_code == 3: is True. So, "Dispensing Juice..." is printed, cost is set to 2.00, and the rest of the elif/else structure is skipped.
4. Finally, "Your drink costs $2.00." is printed.

If drink_code were 99, all if and elif conditions would be False, and the else block would execute, printing "Invalid code. Please try again." and setting cost to 0.00.

4. Key Takeaways

  • elif allows you to test multiple conditions in sequence after an initial if.
  • Only one block of code within an if/elif/else sequence will ever execute.
  • Conditions are evaluated from top to bottom; the first True condition's block runs, and the rest are skipped.
  • The else block is a default; it runs only if all preceding if and elif conditions are False.
  • elif and else are optional, but elif must follow an if (or another elif), and else must be at the very end.

Common Mistakes to Avoid:
- Putting code that you want to always run outside the if/elif/else block, not inside the else.
- Using multiple independent if statements when you mean to use elif, which can lead to multiple blocks executing when you only want one.
- Forgetting the colon : at the end of if, elif, or else lines.
- Incorrectly indenting the code blocks, which changes their execution scope.

5. Now Try It

Write a program that takes a user's age as input (an integer). Then, use if, elif, and else to print a message based on the age:
- If age is less than 13, print "You are a child."
- If age is between 13 and 19 (inclusive), print "You are a teenager."
- If age is 20 or older, print "You are an adult."

What success looks like: Your program should correctly categorize ages like 10, 15, and 25, printing only one message for each.

Frequently asked about Complex Control Flow with 'elif' and 'else'

When you need to check multiple conditions sequentially, elif allows you to test additional cases after an initial if statement. The else block acts as a catch-all, running its code if none of the preceding if or elif conditions were true. Read the full notes above for the details.

Complex Control Flow with 'elif' and 'else' is a core topic in csc241\. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.
Continue with
Logical Operators: 'or' for Alternative Conditions

More from csc241\


Get the full csc241\ curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Save this course free