Is switch option available in Python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • psbasha
    Contributor
    • Feb 2007
    • 440

    #1

    Is switch option available in Python?

    Hi,

    I came across only "if-else,if-elif,nested if else " in some of the Python links,whether we have the similar to "switch" option in Python.

    Thanks in advance
    PSB
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by psbasha
    Hi,

    I came across only "if-else,if-elif,nested if else " in some of the Python links,whether we have the similar to "switch" option in Python.

    Thanks in advance
    PSB
    There's no switch, but it's eazy to build a lookup table:
    Code:
    def func1():
        pass
    
    def func2():
        pass
    
    funcList = (func1, func2)
    
    switchIndex = 0
    
    funcList(switchIndex)()

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      just for information you can see this PEP
      in Python, you can simulate switch using dictionaries, like what barton says a lookup table. eg
      Code:
      switch = {'option1': function1,
           'option2': function2,
           'option3': function3,
           'option4': function4}
      if value in switch:
           switch[value]()
      else:
           pass

      Comment

      Working...