Module 6: Advanced Decisions - else & elif

Handling alternative paths and multiple conditions.

Branching Structures

Beyond a simple `if`, we use `else` for alternatives and `elif` for checking multiple conditions. Click the parts to learn their roles.

if / else

if time < 12: print("Morning") else: print("Afternoon/Evening")

if / elif / else

if grade >= 90: print("A") elif grade >= 80: print("B") else: print("C or below")

Identify all parts in both examples!

Predict the Path

Only one block (`if`, `elif`, or `else`) will run. Given the input value, predict which message will be printed by the code below.

Code Challenge: Temp Check

Write code using `if`, `elif`, and `else` to handle multiple temperature ranges.

Task: Assume a variable `temperature = 25`. Write Python code that checks the temperature and prints:
  • "Hot" if temperature is greater than 30.
  • "Warm" if temperature is greater than or equal to 20 (but not > 30).
  • "Cold" otherwise (if less than 20).
Output will appear here...

Computational Thinking Enhanced

How do `else` and `elif` expand our computational problem-solving?

Introducing `else` and `elif` significantly enhances Algorithmic Thinking by allowing for more complex decision structures.

  • `else` provides a default action, ensuring the algorithm always does *something* even if the initial `if` condition isn't met. This mirrors real-world "otherwise" scenarios.
  • `elif` enables checking multiple, mutually exclusive conditions sequentially. This is crucial for tasks like categorization (e.g., grading, temperature ranges) where only one outcome should apply.
These constructs let us build algorithms that handle a wider variety of inputs and situations gracefully, making them more robust and precise in their logic.

Advanced Practice Complete!

Fantastic! You've mastered `else` and `elif` for more complex decision-making.
Consolidate your understanding by watching the Video Lesson for Module 6.