Module 7: Handling Alternatives

Making decisions with Python: Introducing the `else` statement.

🤔 What if the Condition is False?

We've seen how `if` lets our programs react when something is True. But what happens if the condition isn't met? Sometimes, we need a specific alternative action.

This is where the `else` statement comes in. It provides a second path for our program's logic – the "otherwise" option.

This introduces branching logic, a core part of algorithmic thinking.

🚦 A Fork in the Road

Think of `if/else` like choosing a path based on a condition.

Condition: Is it raining?

IF True

Take an umbrella.

ELSE (False)

Wear sunglasses.

`if/else` allows your program to execute one block of code OR another, but never both based on the condition.

🐍 Python `if/else` Syntax

Let's see how it looks in code.

age = 17 # Assign a valueif age >= 18: # Check the conditionprint("Adult access granted.") # Runs if Trueelse: # If the condition was Falseprint("Minor access only.") # Runs if False

The structure is straightforward:

  • The ifStarts the conditional block. Checks if the following condition is True. keyword starts the check.
  • Followed by the condition (e.g., `age >= 18`) and a colon :Required at the end of `if` and `else` lines. Signals the start of an indented block..
  • The indented block below `if` runs only if the condition is True.
  • The elseIntroduces the alternative block. Runs only if the `if` condition was False. keyword, also followed by a colon :, introduces the alternative.
  • The indented block below `else` runs only if the `if` condition was False.

Indentation (the spaces before `print`) is crucial in Python! It defines which code belongs to the `if` and which belongs to the `else`.

🧠 Quick Check!

Module 7 Theory Complete!

Excellent! You've learned how to create alternative paths in your code using `if/else`. This branching logic is fundamental to programming.
Time to practice making choices in the Practice Zone or tackle more complex scenarios in the Advanced Practice.