A program sometimes needs to choose among several possible actions. In Python, chained decisions use if, elif, and optionally else to check conditions in sequence. This lesson explains how the chain works and how to use it for tasks such as assigning crochet hook sizes or identifying a color from a wavelength.
Two separate if statements are evaluated independently. If both conditions are true, both bodies can run. That can cause unintended results when a program is meant to choose only one action.
All flashcards
What does `elif` mean in Python?
“Else if”: it checks a condition only when all earlier conditions in the chain were false.
How does Python choose a branch in an if-elif chain?
Python checks conditions from top to bottom and runs the body for the first condition that is true. It skips the remaining branches in that chain.
What is the purpose of `else` at the end of a chain?
The `else` body provides a default action. It runs when every preceding `if` and `elif` condition is false.
Why can two separate `if` statements cause an unintended result?
They are independent, so both bodies can run. A change made in the first body can also affect whether the second condition is true.
A wavelength classifier assigns 500–564 nm to green. What color does it assign to 550 nm?
Green, because 550 nm is within the 500–564 nm range.
Quiz questions
When does Python check the condition in an `elif` branch?Answer: Only when the conditions in all preceding `if` or `elif` branches in that chain are false.
What can happen when two independent `if` statements are used for alternatives?Answer: Both bodies can run if both conditions are true.
In an `if`-`elif`-`else` chain, when does the `else` body run?Answer: When every preceding `if` and `elif` condition is false.
A crochet-size program starts `diameter` at -1.0 and has branches for sizes B through G. What happens for an unsupported size?Answer: No size branch matches, so `diameter` remains -1.0.
A Python `if`-`elif` chain has a special case `x >= 20` and a general case `x >= 10`. For `x = 25`, which ordering makes the special-case body run?Answer: Check `x >= 20` before `x >= 10`.
Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.