4.5. Chained conditionals¶
Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:
elif
is an abbreviation of “else if.” Again, exactly one
branch will be executed.
There is no limit on the number of elif
statements. If
there is an else
clause, it has to be at the end, but there
doesn’t have to be one.
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.
- a
- While the value in x is less than the value in y (3 is less than 5) it is not less than the value in z (3 is not less than 2).
- b
- The value in y is not less than the value in x (5 is not less than 3).
- c
- Since the first two Boolean expressions are false the else will be executed.
Q-3: What will the following code print if x = 3, y = 5, and z = 2?
if x < y and x < z:
print("a")
elif y < x and y < z:
print("b")
else:
print("c")
- A
- Because the first statement is satisfied, it does not continue to the following elif or else statements.
- B
- Try again. This code skips the elif/else statements once an if/elif statement has been satisfied.
- C
- Try again. This code skips the elif/else statements once an if/elif statement has been satisfied.
- D
- Try again. This code skips the elif/else statements once an if/elif statement has been satisfied.
- E
- This will only be true when score does not satisfy the other if/elif statements (so it will only execute when score < 60).
Q-4: If score = 93, what will print when the following code executes?
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "E"
print(grade)
- A
- Notice that each of the first 4 statements start with an if. What is the value of grade when it is printed?
- B
- Each of the first 4 if statements will execute.
- C
- Copy this code to an activecode window and run it.
- D
- Each of the first 4 if statements will be executed. So grade will be set to A, then B then C and finally D.
- E
- This will only be true when score is less than 60.
Q-5: If score = 93, what will print when the following code executes?
if score >= 90:
grade = "A"
if score >= 80:
grade = "B"
if score >= 70:
grade = "C"
if score >= 60:
grade = "D"
if score < 60:
grade = "E"
print(grade)