< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204175202199143109011240040

elif (a.k.a. else-if) Statement

elif is the Python else-if statement. It allows one to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true. Like the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.

					
if
						expression1:
   expr1_true_suite
elif
						expression2:
   expr2_true_suite
         :
elif
						expressionN:
   exprN_true_suite
else:
   none_of_the_above_suite

				

At this time, Python does not currently support switch or case statements as in other languages. Python syntax does not present roadblocks to readability in the presence of a good number of if-elif statements.

					
if (user.cmd == 'create'):
    action = "create item"
    valid = 1

elif (user.cmd == 'delete'):
    action = 'delete item'
    valid = 1

elif (user.cmd == 'quit'):
    action = 'quit item'
    valid = 1

else:
    action = "invalid choice… try again!"
    valid = 0

				

Python presents an elegant alternative to the switch/case statement in the for statement. Using for, one can "simulate" switches by cycling through each potential "case," and take action when warranted. (See Section 8.5.3.)


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.