Lesson 02-10: Ordering of Conditionals¶
Learning Target: I can predict the outcome of if/elif/else statements based on their order.
Order Matters¶
What happens if multiple conditions throughout the if
//elif
conditions are being satisfied? Run the code below:
Notice that even though number
is greater than 2, 4, and 8, satisfying all three conditions, only "Greater than 2!"
gets printed. Why is that?
-
ch0210-1: Why is “Greater than 2!” printed instead of any of the other options?
- (A) the "if number greater than 2" is checked first
- Order matters!
- (B) 2 is the smallest of (2,5,8)
- The value itself doesn't matter much here.
- (C) it only checks the if statement
- If the if statement were false, it would still continue!
Here we can see clearly that the ordering within if statements matter! This is especially true for conditionals that “overlap” in some ways