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

Checks For Understanding

Q#1

ch0210-2: Rearrange the following conditions to ensure that every if statement is accessible.

Drag from here

elif x > 50: print("fiftys")
elif x > 10: print("tens")
elif x > 1: print("ones")
if x > 100: print("hundreds")

Drop blocks here

Next Section - Lesson 02-11: Checking for Divisibility