7.7. Chained conditionalsΒΆ
Python provides an alternative way to write nested selection such as the one shown in the previous section. This is sometimes referred to as a chained conditional
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x and y must be equal")
The flow of control can be drawn in a different orientation but the resulting pattern is identical to the one shown above.
elif
is an abbreviation of else if
. Again, exactly one branch will be
executed. There is no limit of the number of elif
statements but only a
single (and optional) final else
statement is allowed and it must be the last
branch in the statement.
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.
Here is the same program using elif
.
Note
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
Check your understanding
- (A) I only
- You can not use a Boolean expression after an else.
- (B) II only
- Yes, II will give the same result.
- (C) III only
- No, III will not give the same result. The first if statement will be true, but the second will be false, so the else part will execute.
- (D) II and III
- No, Although II is correct III will not give the same result. Try it.
- (E) I, II, and III
- No, in I you can not have a Boolean expression after an else.
select-7-1: Which of I, II, and III below gives the same result as the following nested if?
# nested if-else statement
x = -10
if x < 0:
print("The negative number ", x, " is not valid here.")
else:
if x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
I.
if x < 0:
print("The negative number ", x, " is not valid here.")
else x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
II.
if x < 0:
print("The negative number ", x, " is not valid here.")
elif x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
III.
if x < 0:
print("The negative number ", x, " is not valid here.")
if x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
- (A) 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) b
- The value in y is not less than the value in x (5 is not less than 3).
- (C) c
- Since the first two Boolean expressions are false the else will be executed.
select-7-2: 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")