Python also supports if-elif-else statement to test additional conditions apart from the initial test expression. The if-elif-else construct works in the same way as a usual if-else statement. If-elif-else construct is also known as nested-if construct.
The syntax of if-elif-else statement is given below.
if condition1: statement1 elif condition2: statement2 elif condition3: statement3 else: statement4
When condition1 is True, the statement1 will be executed. If condition1 is False, then condition2 is evaluated. When condition2 is True, the statement2 will be executed. When condition2 is False, the condition3 is tested. If condition3 is True, then statement3 will be executed. When condition3 is False the statement4 will be executed. It means statement4 will be executed only if none of the conditions are True.
Observe the colon (:) after each condition. The statement1, statement2, statement3 …. represents one statement or a suite. The final else part is not compulsory. It means, it is possible to write if-elif statement without else and statement4.
Let’s write a program to understand how if-elif-else works.
num = int(input("Enter any number: ")) if (num == 0): print("The value is equal to zero.") elif (num > 0): print("The number is positive.") else: print("The number is negative.")
#output Enter any number: -100 The number is negative.
The above program checks whether a number is positive or negative. A number becomes positive when it is greater than 0. A number becomes negative when it is lesser than 0. Apart from positive and negative, a number can also become zero (neither +ve or -ve). All these combinations are checked in the program. Observe the indentations. There are 4 spaces before every statement after colon.
Let’s write another program to determine whether the character entered is a vowel or not.
ch = input("Enter any character: ") if (ch=='A' or ch=='E' or ch=='I' or ch=='O' or ch=='U'): print(ch, 'is a vowel.') elif (ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u'): print(ch, 'is a vowel.') else: print(ch, 'is not a vowel.')
#output Enter any character: z z is not a vowel.