Module 8: Handling Choices with `elif`

Making complex decisions in your Python code for smarter AI.

🤔 Beyond Just Two Options

Sometimes, a simple "if this, then that, otherwise this other thing" isn't enough. What if you have multiple possibilities to check?

Imagine grading an exam: Is it an A? Or maybe a B? Or a C? Or something else? We need a way to check several conditions one after another.

Python's `elif` (short for "else if") lets us build these multi-step decision paths cleanly.

🏗️ The `if / elif / else` Structure

Python checks conditions sequentially until one is TRUE.

Check `if` condition
FALSE
Check `elif` condition
FALSE
(More `elif` checks...)
ALL FALSE
Execute `else` block
Execute `if` block & STOP
Execute `elif` block & STOP
score = 85 grade = "" # Check conditions one by one if score >= 90: grade = "A" elif score >= 80: # This one is TRUE! grade = "B" # Code inside runs elif score >= 70: # Skipped grade = "C" else: # Also skipped grade = "D" print(f"The grade is: {grade}") # Output: B

Key points: Use : after conditions and indent the code blocks underneath. Only one block (the first one whose condition is `True`) will run!

🧠 Quick Check!

Module 8 Theory Complete!

Excellent work navigating multiple conditions with `elif`! You're building more complex decision-making skills.
Solidify your learning in the Practice Zone or tackle advanced challenges.