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.
elif is an abbreviation of else if. Exactly one branch will be executed. There is no limit on 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.
The following image highlights different kinds of valid conditionals that can be used. Though there are other versions of conditionals that Python can understand (imagine an if statement with twenty elif statements), those other versions must follow the same order as seen below.
# 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")
Create one conditional to find whether βfalseβ is in string str1. If so, assign variable output the string βFalse. You arenβt you?β. Check to see if βtrueβ is in string str1 and if it is then assign βTrue! You are you!β to the variable output. If neither are in str1, assign βNeither true nor false!β to output.