if elif else in Python

if-elif-else in Python

When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.


if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
statements-block n

In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-block1 is executed, otherwise the control checks condition-2, if it is true statementsblock2 is executed and even if it fails statements-block n mentioned in else part is executed.

‘elif’ clause combines if..else-if..else statements to one if..elif…else. ‘elif’ can be considered to be abbreviation of ‘else if’. In an ‘if’ statement there is no limit of ‘elif’ clause that can be used, but an ‘else’ clause if used should be placed at the end.

Example : #Program to illustrate the use of nested if statement

m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
print (“Grade : E”)

Output 1:

Enter mark in first subject : 34

Enter mark in second subject : 78

Grade : D

Output 2 :

Enter mark in first subject : 67

Example : #Program to illustrate the use of ‘in’ and ‘not in’ in if statement

ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)

Output 1:

Enter a character :e

e is a vowel

Output 2:

Enter a character :x

x the letter is not a/b/c

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz