- Use the
elsekeyword to create an alternative path for a false condition. - Write a complete
if/elsecontrol structure. - Understand that in an
if/elseblock, exactly one of the two paths will always be executed.
Creating a True Fork in the Road
A simple if statement is useful, but it has a limitation: it only does something special when the condition is True. If the condition is False, it does nothing. What if we want to provide an alternative action? For that, we use the else keyword.
The if/else Statement
The if/else structure says: "If this condition is true, run the first block of code. Otherwise (if the condition is false), run the second block of code."
if some_condition_is_true:
This indented block runs if the condition is True.
do_this() else:
This indented block runs if the condition is False.
do_that()
With an if/else statement, you are guaranteed that one and only one of the blocks will run. The program must choose one of the two paths; it can never choose both, and it can never choose neither.
Live Example: An Improved Age Checker
Let's upgrade our age checker. Now, instead of just staying silent for younger users, our program will provide a specific message for them. This makes our program much more user-friendly.
Your challenge: Just like last time, run the program twice. First, enter an age like 25. Second, enter an age like 14. Notice that this time, you always get one of the two custom messages.
An if/else statement is perfect for "either/or" decisions. But what if you have a situation with multiple possible outcomes, like "too hot," "too cold," or "just right"? For that, we need one more keyword, which we will learn in our next lesson.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.