Section 8.3. elif (aka else-if) Statement


8.3. elif (aka 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


Proxy for switch/case Statement?

At some time in the future, Python may support the switch or case statement, but you can simulate it with various Python constructs. But even a good number of if-elif statements are not that difficult to read in Python:

if user.cmd == 'create':     action = "create item" elif user.cmd == 'delete':     action = 'delete item' elif user.cmd == 'update':     action = 'update item' else:     action = 'invalid choice... try again!'


Although the above statements do work, you can simplify them with a sequence and the membership operator:

if user.cmd in ('create', 'delete', 'update'):     action = '%s item' % user.cmd else:     action = 'invalid choice... try again!'


We can create an even more elegant solution using Python dictionaries, which we learned about in Chapter 7, "Mapping and Set Types."

msgs = {'create': 'create item',     'delete': 'delete item',     'update': 'update item'} default = 'invalid choice... try again!' action = msgs.get(user.cmd, default)


One well-known benefit of using mapping types such as dictionaries is that the searching is very fast compared to a sequential lookup as in the above if-elif-else statements or using a for loop, both of which have to scan the elements one at a time.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net