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:
1
number = 10
2
3
if number > 2:
4
print("Greater than 2!")
5
elif number > 5:
6
print("Greater than 5!")
7
elif number > 8:
8
print("Greater than 8!")
9
(0210_ex_1)
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?
Here we can see clearly that the ordering within if statements matter! This is especially true for conditionals that “overlap” in some ways