What is the syntax of Python if...elif...else statement?



In Python program if..elif..else construct is used if it has ;arge number of logical expressions to be evaluated so that earlier expressions turn out to be true. If you use nested if - else structure, then indent level of subsequent blocks goes on increasing and program becomes difficult to read. This is where elif is handy. Each block of statements under elif is executed if earlier condition false. Last else block is executed when all previous logical expressions fail. All the blocks have same level of indent.

if expression1==True:
    statement(s)
elif expression2==True:
    statement(s)
elif expression3==True:
    statement(s)
else:
    statement(s)

Advertisements