Python supports if-elif-else statements to test additional conditions apart from the initial test expression. This is also known as the nested-if construct.
The syntax of if-elif-else statement is given below:
if(condition 1):
statement block 1
elif(condition 2):
statement block 2
……………………………………………
elif(condition n):
statement block n
else:
default-statement
statement-x
The conditions are evaluated from the top downwards. As soon as the true condition is found, the statement associated with it is executed, and control is transferred to the statement-x. When all n conditions become false, then the final else containing the default statement is executed.
Example 1:
code=int(input("Enter the value of code=")) if(code==1): print("Red") elif(code==2): print("Green") elif(code==3): print("Blue") elif(code==4): print("Yellow") else: print("Orange")
Output:
Enter the value of code=5
Orange
Example 2:
s=input("Enter the character=") if(s=="a" or s=="e" or s=="i" or s=="o" or s=="u"): print(s+" is a vowel") elif(s=="A" or s=="E" or s=="I" or s=="O" or s=="U"): print(s+" is a vowel") else: print(s+" is not a vowel")
Output:
Enter the character=A
A is a vowel
Leave a comment