If there is case where we need more than two possibilities and we need more than two branches then we have to use chained conditional or if-elif-else conditional. The if and else we know and the new term here is elif which is short for else if. The general form of chained condition or if-elif-else conditional can be written as:
Example 1 The user will type the number and the program must give one of the following outputs: The nubmer is positive. The number is equal to zero. The number is negative.
Solution: We will utilize the "input" function that will ask the user to type in the number. This number will be converted to integer using int() and then assigend to a variable \(num\).
if condition1:There is no limit to the number of elif statements. The else clause goes at the end but there doesn't have to be one. If condition1 is True than the indented statement if condition1 is executed. If condition1 is False then the if condition1 is skipped and condition2 is investigated. If condition2 is True than the indented code under elif condition2 is executed. Otherwise the elif condition2 is skipped and the indented statement under else conditional is executed.
indented statement
elif condition2:
indented statement
else:
indented statement
Example 1 The user will type the number and the program must give one of the following outputs: The nubmer is positive. The number is equal to zero. The number is negative.
Solution: We will utilize the "input" function that will ask the user to type in the number. This number will be converted to integer using int() and then assigend to a variable \(num\).
num = int(input("Enter a number: "))The variable "num" will be investigated if its greater than 0 if it is equal to 0 or it is negative. If any of these conditions are true it will print one of the following messages: The number is positive. The number is equal to zero. The number is negative. This will be done using if-elif-else conditional.
if num > 0:The entire code for this example is given below.
print("The number is positive!")
elif num == 0:
print("The number is equal to 0!")
else:
print("The number is negative!")
num = int(input("Enter a number: "))The previous code has three posible outputs. The first output is that the number is positive so when runing the code we will type the nubmer 5. The output is given below.
if num > 0:
print("The number is positive!")
elif num == 0:
print("The number is equal to 0!")
else:
print("The number is negative!")
Enter a number: 5The second output is "The number is equal to zero." so when we run the code we will type the number 0. The output is given below.
The number is positive!
Enter a number: 0The last program output is that the number is negative so when we run the code we will type number -5. The output is given below.
The number is equal to 0!
Enter a number: -5
The number is negative!