Posted By

magicrebirth on 12/22/09


Tagged

Switch case


Versions (?)

Python: switch statement (a replacement of..)


 / Published in: Python
 

  1. ## There is currently no switch statement in Python. Often this is not a problem and can be handled through a series of if-elif-else statements. However, there are many other ways to handle the deficiency. The following example shows how to create a simple switch statement in Python:
  2.  
  3. >>>def a(s):
  4. >>> print s
  5. >>>def switch(ch):
  6. >>> try:
  7. >>> {'1': lambda : a("one"),
  8. >>> '2': lambda : a("two"),
  9. >>> '3': lambda : a("three"),
  10. >>> 'a': lambda : a("Letter a")
  11. >>> }[ch]()
  12. >>> except KeyError:
  13. >>> a("Key not Found")
  14. >>>switch('1')
  15. one
  16. >>>switch('a')
  17. Letter a
  18. >>>switch('b')
  19. Key not Found
  20.  
  21.  
  22. ## Remember that we are making use of the following method for checking the existence of a Key...:
  23.  
  24. >>> {1: 2}[1]
  25. >>> 2
  26. >>> {1: 2}[0]
  27. Key Error......
  28.  
  29.  
  30. ## p.s. check also the entry about the use of lambda in a dictionary...

Report this snippet  

You need to login to post a comment.