Switch/Case Statement Proxy

Earlier in previous programs, we introduced the if-elif-else construct and indicated that Python did not support a switch/case statement. In many cases, an incredibly long set of if-elif-else statements can be replaced by a for loop, which contains the “case” items in a sequence which is iterated over. Consider the following alternative approach for switch :


>>> for amd in ('add','delete','quit'):
    if cmd== user.cmd:
        action = amd + "item"
        valid = 1
        action = "invalid choice"
        valid = 0

You are now probably glad to see that there is some kind of substitute for the lack of a switch/case statement in Python, but do you realize that using a list gives you even more power as a programmer? In other languages, the elements of a case statement are constant and a static part of the code. By using lists in Python, not only can these elements be variables, but they can also be dynamic and changed during run-time!
Final note, it may have surprised you to see an else statement at the end there.Yes, else statements can be used with for loops. In this case, the else clause is executed only if the for loop finished to completion.


You may also like...