<p>I want to write a function in Python that returns different fixed values based on the value of an input index.  </p>

<p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement.  What are the recommended Python solutions in this scenario?</p>

[{'answer_id': 60211, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 12, 'selected': True, 'text': '<p>The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the <a href="https://www.python.org/dev/peps/pep-0634/" rel="noreferrer"><code>match</code>-<code>case</code></a> statement which provides a first-class implementation of a &quot;switch&quot; for Python. For example:</p>\n<pre><code>def f(x):\n    match x:\n        case \'a\':\n            return 1\n        case \'b\':\n            return 2\n        case _:\n            return 0   # 0 is the default case if x is not found\n</code></pre>\n<p>The <code>match</code>-<code>case</code> statement is considerably more powerful than this simple example.</p>\n<hr />\n<p>You could use a dictionary:</p>\n<pre><code>def f(x):\n    return {\n        \'a\': 1,\n        \'b\': 2,\n    }[x]\n</code></pre>\n'}, {'answer_id': 60215, 'author': 'Mark Biek', 'author_id': 305, 'author_profile': 'https://Stackoverflow.com/users/305', 'pm_score': 9, 'selected': False, 'text': '<p>I\'ve always liked doing it this way</p>\n\n<pre><code>result = {\n  \'a\': lambda x: x * 5,\n  \'b\': lambda x: x + 7,\n  \'c\': lambda x: x - 2\n}[value](x)\n</code></pre>\n\n<p><a href="http://blog.simonwillison.net/post/57956755106/switch" rel="noreferrer">From here</a></p>\n'}, {'answer_id': 60216, 'author': 'Eugene', 'author_id': 1155, 'author_profile': 'https://Stackoverflow.com/users/1155', 'pm_score': 2, 'selected': False, 'text': '<p>If you are really just returning a predetermined, fixed value, you could create a dictionary with all possible input indexes as the keys, along with their corresponding values. Also, you might not really want a function to do this - unless you\'re computing the return value somehow.</p>\n\n<p>Oh, and if you feel like doing something switch-like, see <a href="https://web.archive.org/web/20120216013404/http://www.mustap.com/pythonzone_post_224_python-switch-statement?" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 60236, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 9, 'selected': False, 'text': "<p>In addition to the dictionary methods (which I really like, BTW), you can also use <code>if</code>-<code>elif</code>-<code>else</code> to obtain the <code>switch</code>/<code>case</code>/<code>default</code> functionality:</p>\n\n<pre><code>if x == 'a':\n    # Do the thing\nelif x == 'b':\n    # Do the other thing\nif x in 'bc':\n    # Fall-through by not using elif, but now the default case includes case 'a'!\nelif x in 'xyz':\n    # Do yet another thing\nelse:\n    # Do the default\n</code></pre>\n\n<p>This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the <code>break</code> statement, but you can have a more complicated test. Its formatting is nicer than a series of nested <code>if</code>s, even though functionally that's what it is closer to.</p>\n"}, {'answer_id': 60243, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': "<p>There's a pattern that I learned from Twisted Python code.</p>\n\n<pre><code>class SMTP:\n    def lookupMethod(self, command):\n        return getattr(self, 'do_' + command.upper(), None)\n    def do_HELO(self, rest):\n        return 'Howdy ' + rest\n    def do_QUIT(self, rest):\n        return 'Bye'\n\nSMTP().lookupMethod('HELO')('foo.bar.com') # =&gt; 'Howdy foo.bar.com'\nSMTP().lookupMethod('QUIT')('') # =&gt; 'Bye'\n</code></pre>\n\n<p>You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have <code>state_</code> methods, and dispatch on <code>self.state</code>. This switch can be cleanly extended by inheriting from base class and defining your own <code>do_</code> methods. Often times you won't even have <code>do_</code> methods in the base class.</p>\n\n<p><em>Edit: how exactly is that used</em></p>\n\n<p>In case of SMTP you will receive <code>HELO</code> from the wire. The relevant code (from <code>twisted/mail/smtp.py</code>, modified for our case) looks like this</p>\n\n<pre><code>class SMTP:\n    # ...\n\n    def do_UNKNOWN(self, rest):\n        raise NotImplementedError, 'received unknown command'\n\n    def state_COMMAND(self, line):\n        line = line.strip()\n        parts = line.split(None, 1)\n        if parts:\n            method = self.lookupMethod(parts[0]) or self.do_UNKNOWN\n            if len(parts) == 2:\n                return method(parts[1])\n            else:\n                return method('')\n        else:\n            raise SyntaxError, 'bad syntax'\n\nSMTP().state_COMMAND('   HELO   foo.bar.com  ') # =&gt; Howdy foo.bar.com\n</code></pre>\n\n<p>You'll receive <code>'  HELO   foo.bar.com '</code> (or you might get <code>'QUIT'</code> or <code>'RCPT TO: foo'</code>). This is tokenized into <code>parts</code> as <code>['HELO', 'foo.bar.com']</code>. The actual method lookup name is taken from <code>parts[0]</code>.</p>\n\n<p>(The original method is also called <code>state_COMMAND</code>, because it uses the same pattern to implement a state machine, i.e. <code>getattr(self, 'state_' + self.mode)</code>)</p>\n"}, {'answer_id': 102990, 'author': 'Jeremy Cantrell', 'author_id': 18866, 'author_profile': 'https://Stackoverflow.com/users/18866', 'pm_score': 4, 'selected': False, 'text': "<p>Expanding on the &quot;dict as switch&quot; idea. If you want to use a default value for your switch:</p>\n<pre><code>def f(x):\n    try:\n        return {\n            'a': 1,\n            'b': 2,\n        }[x]\n    except KeyError:\n        return 'default'\n</code></pre>\n"}, {'answer_id': 103081, 'author': 'Nick', 'author_id': 3233, 'author_profile': 'https://Stackoverflow.com/users/3233', 'pm_score': 11, 'selected': False, 'text': '<p>If you\'d like defaults, you could use the dictionary <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="noreferrer"><code>get(key[, default])</code></a> function:</p>\n<pre><code>def f(x):\n    return {\n        \'a\': 1,\n        \'b\': 2\n    }.get(x, 9)    # 9 will be returned default if x is not found\n</code></pre>\n'}, {'answer_id': 3129619, 'author': 'thomasf1', 'author_id': 377671, 'author_profile': 'https://Stackoverflow.com/users/377671', 'pm_score': 4, 'selected': False, 'text': '<p>The solutions I use: </p>\n\n<p>A combination of 2 of the solutions posted here, which is relatively easy to read and supports defaults.</p>\n\n<pre><code>result = {\n  \'a\': lambda x: x * 5,\n  \'b\': lambda x: x + 7,\n  \'c\': lambda x: x - 2\n}.get(whatToUse, lambda x: x - 22)(value)\n</code></pre>\n\n<p>where</p>\n\n<pre><code>.get(\'c\', lambda x: x - 22)(23)\n</code></pre>\n\n<p>looks up <code>"lambda x: x - 2"</code> in the dict and uses it with <code>x=23</code> </p>\n\n<pre><code>.get(\'xxx\', lambda x: x - 22)(44)\n</code></pre>\n\n<p>doesn\'t find it in the dict and uses the default <code>"lambda x: x - 22"</code> with <code>x=44</code>.</p>\n'}, {'answer_id': 3828986, 'author': 'GeeF', 'author_id': 190001, 'author_profile': 'https://Stackoverflow.com/users/190001', 'pm_score': 5, 'selected': False, 'text': "<p>Let's say you don't want to just return a value, but want to use methods that change something on an object. Using the approach stated here would be:</p>\n<pre><code>result = {\n  'a': obj.increment(x),\n  'b': obj.decrement(x)\n}.get(value, obj.default(x))\n</code></pre>\n<p>Here Python evaluates all methods in the dictionary.</p>\n<p>So even if your value is 'a', the object will get incremented <strong>and</strong> decremented by x.</p>\n<p>Solution:</p>\n<pre><code>func, args = {\n  'a' : (obj.increment, (x,)),\n  'b' : (obj.decrement, (x,)),\n}.get(value, (obj.default, (x,)))\n\nresult = func(*args)\n</code></pre>\n<p>So you get a list containing a function and its arguments. This way, only the function pointer and the argument list get returned, <em>not</em> evaluated. 'result' then evaluates the returned function call.</p>\n"}, {'answer_id': 4367749, 'author': 'elp', 'author_id': 532453, 'author_profile': 'https://Stackoverflow.com/users/532453', 'pm_score': 4, 'selected': False, 'text': '<p>If you\'re searching extra-statement, as &quot;switch&quot;, I built a Python module that extends Python. It\'s called <a href="https://web.archive.org/web/20111103124355/http://elp.chronocv.fr/articles.php?lng=en&amp;pg=19" rel="nofollow noreferrer">ESPY</a> as &quot;Enhanced Structure for Python&quot; and it\'s available for both Python 2.x and Python 3.x.</p>\n<p>For example, in this case, a switch statement could be performed by the following code:</p>\n<pre><code>macro switch(arg1):\n    while True:\n        cont=False\n        val=%arg1%\n        socket case(arg2):\n            if val==%arg2% or cont:\n                cont=True\n                socket\n        socket else:\n            socket\n        break\n</code></pre>\n<p>That can be used like this:</p>\n<pre><code>a=3\nswitch(a):\n    case(0):\n        print(&quot;Zero&quot;)\n    case(1):\n        print(&quot;Smaller than 2&quot;):\n        break\n    else:\n        print (&quot;greater than 1&quot;)\n</code></pre>\n<p>So espy translate it in Python as:</p>\n<pre><code>a=3\nwhile True:\n    cont=False\n    if a==0 or cont:\n        cont=True\n        print (&quot;Zero&quot;)\n    if a==1 or cont:\n        cont=True\n        print (&quot;Smaller than 2&quot;)\n        break\n    print (&quot;greater than 1&quot;)\n    break\n</code></pre>\n'}, {'answer_id': 6606504, 'author': 'adamh', 'author_id': 832936, 'author_profile': 'https://Stackoverflow.com/users/832936', 'pm_score': 7, 'selected': False, 'text': '<pre><code>class switch(object):\n    value = None\n    def __new__(class_, value):\n        class_.value = value\n        return True\n\ndef case(*args):\n    return any((arg == switch.value for arg in args))\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>while switch(n):\n    if case(0):\n        print "You typed zero."\n        break\n    if case(1, 4, 9):\n        print "n is a perfect square."\n        break\n    if case(2):\n        print "n is an even number."\n    if case(2, 3, 5, 7):\n        print "n is a prime number."\n        break\n    if case(6, 8):\n        print "n is an even number."\n        break\n    print "Only single-digit numbers are allowed."\n    break\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code>n = 2\n#Result:\n#n is an even number.\n#n is a prime number.\nn = 11\n#Result:\n#Only single-digit numbers are allowed.\n</code></pre>\n'}, {'answer_id': 6606540, 'author': 'John Doe', 'author_id': 832391, 'author_profile': 'https://Stackoverflow.com/users/832391', 'pm_score': 6, 'selected': False, 'text': '<p>My favorite one is a really nice <a href="http://code.activestate.com/recipes/410692/" rel="noreferrer">recipe</a>. It\'s the closest one I\'ve seen to actual switch case statements, especially in features.</p>\n<pre class="lang-py prettyprint-override"><code>class switch(object):\n    def __init__(self, value):\n        self.value = value\n        self.fall = False\n\n    def __iter__(self):\n        &quot;&quot;&quot;Return the match method once, then stop&quot;&quot;&quot;\n        yield self.match\n        raise StopIteration\n    \n    def match(self, *args):\n        &quot;&quot;&quot;Indicate whether or not to enter a case suite&quot;&quot;&quot;\n        if self.fall or not args:\n            return True\n        elif self.value in args: # changed for v1.5, see below\n            self.fall = True\n            return True\n        else:\n            return False\n</code></pre>\n<p>Here\'s an example:</p>\n<pre class="lang-py prettyprint-override"><code># The following example is pretty much the exact use-case of a dictionary,\n# but is included for its simplicity. Note that you can include statements\n# in each suite.\nv = \'ten\'\nfor case in switch(v):\n    if case(\'one\'):\n        print 1\n        break\n    if case(\'two\'):\n        print 2\n        break\n    if case(\'ten\'):\n        print 10\n        break\n    if case(\'eleven\'):\n        print 11\n        break\n    if case(): # default, could also just omit condition or \'if True\'\n        print &quot;something else!&quot;\n        # No need to break here, it\'ll stop anyway\n\n# break is used here to look as much like the real thing as possible, but\n# elif is generally just as good and more concise.\n\n# Empty suites are considered syntax errors, so intentional fall-throughs\n# should contain \'pass\'\nc = \'z\'\nfor case in switch(c):\n    if case(\'a\'): pass # only necessary if the rest of the suite is empty\n    if case(\'b\'): pass\n    # ...\n    if case(\'y\'): pass\n    if case(\'z\'):\n        print &quot;c is lowercase!&quot;\n        break\n    if case(\'A\'): pass\n    # ...\n    if case(\'Z\'):\n        print &quot;c is uppercase!&quot;\n        break\n    if case(): # default\n        print &quot;I dunno what c was!&quot;\n\n# As suggested by Pierre Quentel, you can even expand upon the\n# functionality of the classic \'case\' statement by matching multiple\n# cases in a single shot. This greatly benefits operations such as the\n# uppercase/lowercase example above:\nimport string\nc = \'A\'\nfor case in switch(c):\n    if case(*string.lowercase): # note the * for unpacking as arguments\n        print &quot;c is lowercase!&quot;\n        break\n    if case(*string.uppercase):\n        print &quot;c is uppercase!&quot;\n        break\n    if case(\'!\', \'?\', \'.\'): # normal argument passing style also applies\n        print &quot;c is a sentence terminator!&quot;\n        break\n    if case(): # default\n        print &quot;I dunno what c was!&quot;\n</code></pre>\n<p>Some of the comments indicated that a context manager solution using <code>with foo as case</code> rather than <code>for case in foo</code> might be cleaner, and for large switch statements the linear rather than quadratic behavior might be a nice touch. Part of the value in this answer with a for loop is the ability to have breaks and fallthrough, and if we\'re willing to play with our choice of keywords a little bit we can get that in a context manager too:</p>\n<pre><code>class Switch:\n    def __init__(self, value):\n        self.value = value\n        self._entered = False\n        self._broken = False\n        self._prev = None\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        return False # Allows a traceback to occur\n\n    def __call__(self, *values):\n        if self._broken:\n            return False\n        \n        if not self._entered:\n            if values and self.value not in values:\n                return False\n            self._entered, self._prev = True, values\n            return True\n        \n        if self._prev is None:\n            self._prev = values\n            return True\n        \n        if self._prev != values:\n            self._broken = True\n            return False\n        \n        if self._prev == values:\n            self._prev = None\n            return False\n    \n    @property\n    def default(self):\n        return self()\n</code></pre>\n<p>Here\'s an example:</p>\n<pre><code># Prints \'bar\' then \'baz\'.\nwith Switch(2) as case:\n    while case(0):\n        print(\'foo\')\n    while case(1, 2, 3):\n        print(\'bar\')\n    while case(4, 5):\n        print(\'baz\')\n        break\n    while case.default:\n        print(\'default\')\n        break\n</code></pre>\n'}, {'answer_id': 10272369, 'author': 'Asher', 'author_id': 1164146, 'author_profile': 'https://Stackoverflow.com/users/1164146', 'pm_score': 5, 'selected': False, 'text': "<p>If you have a complicated case block you can consider using a function dictionary lookup table...</p>\n<p>If you haven't done this before it's a good idea to step into your debugger and view exactly how the dictionary looks up each function.</p>\n<p>NOTE: Do <em>not</em> use &quot;()&quot; inside the case/dictionary lookup or it will call each of your functions as the dictionary / case block is created.  Remember this because you only want to call each function once using a hash style lookup.</p>\n<pre><code>def first_case():\n    print &quot;first&quot;\n\ndef second_case():\n    print &quot;second&quot;\n\ndef third_case():\n    print &quot;third&quot;\n\nmycase = {\n'first': first_case, #do not use ()\n'second': second_case, #do not use ()\n'third': third_case #do not use ()\n}\nmyfunc = mycase['first']\nmyfunc()\n</code></pre>\n"}, {'answer_id': 13239503, 'author': 'emu', 'author_id': 797845, 'author_profile': 'https://Stackoverflow.com/users/797845', 'pm_score': 3, 'selected': False, 'text': "<pre><code>def f(x):\n     return 1 if x == 'a' else\\\n            2 if x in 'bcd' else\\\n            0 #default\n</code></pre>\n\n<p>Short and easy to read, has a default value and supports expressions in both conditions and return values.</p>\n\n<p>However, it is less efficient than the solution with a dictionary. For example, Python has to scan through all the conditions before returning the default value.</p>\n"}, {'answer_id': 14688688, 'author': 'Alden', 'author_id': 585278, 'author_profile': 'https://Stackoverflow.com/users/585278', 'pm_score': 2, 'selected': False, 'text': "<p>Just mapping some a key to some code is not really an issue as most people have shown using the dict. The real trick is trying to emulate the whole drop through and break thing. I don't think I've ever written a case statement where I used that &quot;feature&quot;. Here's a go at drop through.</p>\n<pre><code>def case(list): reduce(lambda b, f: (b | f[0], {False:(lambda:None),True:f[1]}[b | f[0]]())[0], list, False)\n\ncase([\n    (False, lambda:print(5)),\n    (True, lambda:print(4))\n])\n</code></pre>\n<p>I was really imagining it as a single statement. I hope you'll pardon the silly formatting.</p>\n<pre><code>reduce(\n    initializer=False,\n    function=(lambda b, f:\n        ( b | f[0]\n        , { False: (lambda:None)\n          , True : f[1]\n          }[b | f[0]]()\n        )[0]\n    ),\n    iterable=[\n        (False, lambda:print(5)),\n        (True, lambda:print(4))\n    ]\n)\n</code></pre>\n<p>I hope that's valid Python code. It should give you drop through. Of course the Boolean checks could be expressions and if you wanted them to be evaluated lazily you could wrap them all in a lambda. It wouldn't be to hard to make it accept after executing some of the items in the list either. Just make the tuple (bool, bool, function) where the second bool indicates whether or not to break or drop through.</p>\n"}, {'answer_id': 16964129, 'author': 'Harry247', 'author_id': 2392636, 'author_profile': 'https://Stackoverflow.com/users/2392636', 'pm_score': 1, 'selected': False, 'text': '<p>Also use the <em>list</em> for storing the cases, and call corresponding the function by select -</p>\n<pre><code>cases = [\'zero()\', \'one()\', \'two()\', \'three()\']\n\ndef zero():\n  print &quot;method for 0 called...&quot;\ndef one():\n  print &quot;method for 1 called...&quot;\ndef two():\n  print &quot;method for 2 called...&quot;\ndef three():\n  print &quot;method for 3 called...&quot;\n\ni = int(raw_input(&quot;Enter choice between 0-3 &quot;))\n\nif(i&lt;=len(cases)):\n  exec(cases[i])\nelse:\n  print &quot;wrong choice&quot;\n</code></pre>\n<p>Also explained at <a href="http://screwdesk.com/python-switch-case-alternative/" rel="nofollow noreferrer">screwdesk</a>.</p>\n'}, {'answer_id': 17865871, 'author': 'William H. Hooper', 'author_id': 2619926, 'author_profile': 'https://Stackoverflow.com/users/2619926', 'pm_score': 3, 'selected': False, 'text': '<p>Defining:</p>\n\n<pre><code>def switch1(value, options):\n  if value in options:\n    options[value]()\n</code></pre>\n\n<p>allows you to use a fairly straightforward syntax, with the cases bundled into a map:</p>\n\n<pre><code>def sample1(x):\n  local = \'betty\'\n  switch1(x, {\n    \'a\': lambda: print("hello"),\n    \'b\': lambda: (\n      print("goodbye," + local),\n      print("!")),\n    })\n</code></pre>\n\n<p>I kept trying to redefine switch in a way that would let me get rid of the "lambda:", but gave up.  Tweaking the definition:</p>\n\n<pre><code>def switch(value, *maps):\n  options = {}\n  for m in maps:\n    options.update(m)\n  if value in options:\n    options[value]()\n  elif None in options:\n    options[None]()\n</code></pre>\n\n<p>Allowed me to map multiple cases to the same code, and to supply a default option:</p>\n\n<pre><code>def sample(x):\n  switch(x, {\n    _: lambda: print("other") \n    for _ in \'cdef\'\n    }, {\n    \'a\': lambda: print("hello"),\n    \'b\': lambda: (\n      print("goodbye,"),\n      print("!")),\n    None: lambda: print("I dunno")\n    })\n</code></pre>\n\n<p>Each replicated case has to be in its own dictionary; switch() consolidates the dictionaries before looking up the value.  It\'s still uglier than I\'d like, but it has the basic efficiency of using a hashed lookup on the expression, rather than a loop through all the keys.</p>\n'}, {'answer_id': 19335626, 'author': 'JD Graham', 'author_id': 2874221, 'author_profile': 'https://Stackoverflow.com/users/2874221', 'pm_score': 4, 'selected': False, 'text': '<p>I didn\'t find the simple answer I was looking for anywhere on Google search. But I figured it out anyway. It\'s really quite simple. Decided to post it, and maybe prevent a few less scratches on someone else\'s head. The key is simply "in" and tuples. Here is the switch statement behavior with fall-through, including RANDOM fall-through.</p>\n\n<pre><code>l = [\'Dog\', \'Cat\', \'Bird\', \'Bigfoot\',\n     \'Dragonfly\', \'Snake\', \'Bat\', \'Loch Ness Monster\']\n\nfor x in l:\n    if x in (\'Dog\', \'Cat\'):\n        x += " has four legs"\n    elif x in (\'Bat\', \'Bird\', \'Dragonfly\'):\n        x += " has wings."\n    elif x in (\'Snake\',):\n        x += " has a forked tongue."\n    else:\n        x += " is a big mystery by default."\n    print(x)\n\nprint()\n\nfor x in range(10):\n    if x in (0, 1):\n        x = "Values 0 and 1 caught here."\n    elif x in (2,):\n        x = "Value 2 caught here."\n    elif x in (3, 7, 8):\n        x = "Values 3, 7, 8 caught here."\n    elif x in (4, 6):\n        x = "Values 4 and 6 caught here"\n    else:\n        x = "Values 5 and 9 caught in default."\n    print(x)\n</code></pre>\n\n<p>Provides:</p>\n\n<pre><code>Dog has four legs\nCat has four legs\nBird has wings.\nBigfoot is a big mystery by default.\nDragonfly has wings.\nSnake has a forked tongue.\nBat has wings.\nLoch Ness Monster is a big mystery by default.\n\nValues 0 and 1 caught here.\nValues 0 and 1 caught here.\nValue 2 caught here.\nValues 3, 7, 8 caught here.\nValues 4 and 6 caught here\nValues 5 and 9 caught in default.\nValues 4 and 6 caught here\nValues 3, 7, 8 caught here.\nValues 3, 7, 8 caught here.\nValues 5 and 9 caught in default.\n</code></pre>\n'}, {'answer_id': 27212138, 'author': 'guneysus', 'author_id': 1766716, 'author_profile': 'https://Stackoverflow.com/users/1766716', 'pm_score': 3, 'selected': False, 'text': '<p>I liked <a href="https://stackoverflow.com/a/60215/1766716">Mark Bies\'s answer</a></p>\n\n<p>Since the <code>x</code> variable must used twice, I modified the lambda functions to parameterless.</p>\n\n<p>I have to run with  <code>results[value](value)</code></p>\n\n<pre><code>In [2]: result = {\n    ...:   \'a\': lambda x: \'A\',\n    ...:   \'b\': lambda x: \'B\',\n    ...:   \'c\': lambda x: \'C\'\n    ...: }\n    ...: result[\'a\'](\'a\')\n    ...: \nOut[2]: \'A\'\n\nIn [3]: result = {\n    ...:   \'a\': lambda : \'A\',\n    ...:   \'b\': lambda : \'B\',\n    ...:   \'c\': lambda : \'C\',\n    ...:   None: lambda : \'Nothing else matters\'\n\n    ...: }\n    ...: result[\'a\']()\n    ...: \nOut[3]: \'A\'\n</code></pre>\n\n<p><strong>Edit:</strong> I noticed that I can use <code>None</code> type with with dictionaries. So this would emulate <code>switch ; case else</code></p>\n'}, {'answer_id': 27746465, 'author': 'leo', 'author_id': 652066, 'author_profile': 'https://Stackoverflow.com/users/652066', 'pm_score': 4, 'selected': False, 'text': '<p>I found that a common switch structure:</p>\n<pre><code>switch ...parameter...\ncase p1: v1; break;\ncase p2: v2; break;\ndefault: v3;\n</code></pre>\n<p>can be expressed in Python as follows:</p>\n<pre><code>(lambda x: v1 if p1(x) else v2 if p2(x) else v3)\n</code></pre>\n<p>or formatted in a clearer way:</p>\n<pre><code>(lambda x:\n     v1 if p1(x) else\n     v2 if p2(x) else\n     v3)\n</code></pre>\n<p>Instead of being a statement, the Python version is an expression, which evaluates to a value.</p>\n'}, {'answer_id': 30012053, 'author': 'Ian Bell', 'author_id': 4858820, 'author_profile': 'https://Stackoverflow.com/users/4858820', 'pm_score': 6, 'selected': False, 'text': '<pre class="lang-py prettyprint-override"><code>class Switch:\n    def __init__(self, value):\n        self.value = value\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, value, traceback):\n        return False # Allows a traceback to occur\n\n    def __call__(self, *values):\n        return self.value in values\n\n\nfrom datetime import datetime\n\nwith Switch(datetime.today().weekday()) as case:\n    if case(0):\n        # Basic usage of switch\n        print("I hate mondays so much.")\n        # Note there is no break needed here\n    elif case(1,2):\n        # This switch also supports multiple conditions (in one line)\n        print("When is the weekend going to be here?")\n    elif case(3,4):\n        print("The weekend is near.")\n    else:\n        # Default would occur here\n        print("Let\'s go have fun!") # Didn\'t use case for example purposes\n</code></pre>\n'}, {'answer_id': 30881320, 'author': 'ChaimG', 'author_id': 2529619, 'author_profile': 'https://Stackoverflow.com/users/2529619', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Python &gt;= 3.10</strong></p>\n<p>Wow, Python 3.10+ now has a <a href="https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching" rel="noreferrer"><code>match</code>/<code>case</code></a> syntax which is like <code>switch/case</code> and more!</p>\n<p><a href="https://www.python.org/dev/peps/pep-0634/" rel="noreferrer">PEP 634 -- Structural Pattern Matching</a></p>\n<p><strong>Selected features of <code>match/case</code></strong></p>\n<p>1 - Match values:</p>\n<p>Matching values is similar to a simple <code>switch/case</code> in another language:</p>\n<pre><code>match something:\n    case 1 | 2 | 3:\n        # Match 1-3.\n    case _:\n        # Anything else.\n        # \n        # Match will throw an error if this is omitted \n        # and it doesn\'t match any of the other patterns.\n</code></pre>\n<p>2 - Match structural patterns:</p>\n<pre><code>match something:\n    case str() | bytes():  \n        # Match a string like object.\n    case [str(), int()]:\n        # Match a `str` and an `int` sequence \n        # (`list` or a `tuple` but not a `set` or an iterator). \n    case [_, _]:\n        # Match a sequence of 2 variables.\n        # To prevent a common mistake, sequence patterns don’t match strings.\n    case {&quot;bandwidth&quot;: 100, &quot;latency&quot;: 300}:\n        # Match this dict. Extra keys are ignored.\n</code></pre>\n<p>3 - Capture variables</p>\n<p>Parse an object; saving it as variables:</p>\n<pre><code>match something:\n    case [name, count]\n        # Match a sequence of any two objects and parse them into the two variables.\n    case [x, y, *rest]:\n        # Match a sequence of two or more objects, \n        # binding object #3 and on into the rest variable.\n    case bytes() | str() as text:\n        # Match any string like object and save it to the text variable.\n</code></pre>\n<p>Capture variables can be useful when parsing data (such as JSON or HTML) that may come in one of a number of different patterns.</p>\n<p>Capture variables is a feature. But it also means that you need to use dotted constants (ex: <code>COLOR.RED</code>) only. Otherwise, the constant will be treated as a capture variable and overwritten.</p>\n<p><a href="https://docs.python.org/3.10/tutorial/controlflow.html#match-statements" rel="noreferrer">More sample usage</a>:</p>\n<pre><code>match something:\n    case 0 | 1 | 2:\n        # Matches 0, 1 or 2 (value).\n        print(&quot;Small number&quot;)\n    case [] | [_]:\n        # Matches an empty or single value sequence (structure).\n        # Matches lists and tuples but not sets.\n        print(&quot;A short sequence&quot;)\n    case str() | bytes():\n        # Something of `str` or `bytes` type (data type).\n        print(&quot;Something string-like&quot;)\n    case _:\n        # Anything not matched by the above.\n        print(&quot;Something else&quot;)\n</code></pre>\n<hr />\n<p><strong>Python &lt;= 3.9</strong></p>\n<p>My favorite Python recipe for switch/case was:</p>\n<pre><code>choices = {\'a\': 1, \'b\': 2}\nresult = choices.get(key, \'default\')\n</code></pre>\n<p>Short and simple for simple scenarios.</p>\n<p>Compare to 11+ lines of C code:</p>\n<pre><code>// C Language version of a simple \'switch/case\'.\nswitch( key ) \n{\n    case \'a\' :\n        result = 1;\n        break;\n    case \'b\' :\n        result = 2;\n        break;\n    default :\n        result = -1;\n}\n</code></pre>\n<p>You can even assign multiple variables by using tuples:</p>\n<pre><code>choices = {\'a\': (1, 2, 3), \'b\': (4, 5, 6)}\n(result1, result2, result3) = choices.get(key, (\'default1\', \'default2\', \'default3\'))\n</code></pre>\n'}, {'answer_id': 31995013, 'author': 'user5224656', 'author_id': 5224656, 'author_profile': 'https://Stackoverflow.com/users/5224656', 'pm_score': 4, 'selected': False, 'text': "<pre><code># simple case alternative\n\nsome_value = 5.0\n\n# this while loop block simulates a case block\n\n# case\nwhile True:\n\n    # case 1\n    if some_value &gt; 5:\n        print ('Greater than five')\n        break\n\n    # case 2\n    if some_value == 5:\n        print ('Equal to five')\n        break\n\n    # else case 3\n    print ( 'Must be less than 5')\n    break\n</code></pre>\n"}, {'answer_id': 36079070, 'author': 'J_Zar', 'author_id': 1351609, 'author_profile': 'https://Stackoverflow.com/users/1351609', 'pm_score': 3, 'selected': False, 'text': '<p>I think the best way is to <strong>use the Python language idioms to keep your code testable</strong>. As showed in previous answers, I use dictionaries to <strong>take advantage of python structures and language</strong> and keep the &quot;case&quot; code isolated in different methods. Below there is a class, but you can use directly a module, globals and functions. The class has methods that <strong>can be tested with isolation</strong>.</p>\n<p>Depending to your needs, you can play with static methods and attributes too.</p>\n<pre><code>class ChoiceManager:\n\n    def __init__(self):\n        self.__choice_table = \\\n        {\n            &quot;CHOICE1&quot; : self.my_func1,\n            &quot;CHOICE2&quot; : self.my_func2,\n        }\n\n    def my_func1(self, data):\n        pass\n\n    def my_func2(self, data):\n        pass\n\n    def process(self, case, data):\n        return self.__choice_table[case](data)\n\nChoiceManager().process(&quot;CHOICE1&quot;, my_data)\n</code></pre>\n<p>It is possible to <strong>take advantage of this method using also classes as keys</strong> of &quot;__choice_table&quot;. In this way you can avoid <em>isinstance abuse</em> and keep all clean and testable.</p>\n<p>Supposing you have to process a lot of messages or packets from the net or your MQ. Every packet has its own structure and its management code (in a generic way).</p>\n<p>With the above code it is possible to do something like this:</p>\n<pre><code>class PacketManager:\n\n    def __init__(self):\n        self.__choice_table = \\\n        {\n            ControlMessage : self.my_func1,\n            DiagnosticMessage : self.my_func2,\n        }\n\n    def my_func1(self, data):\n        # process the control message here\n        pass\n\n    def my_func2(self, data):\n        # process the diagnostic message here\n        pass\n\n    def process(self, pkt):\n        return self.__choice_table[pkt.__class__](pkt)\n\npkt = GetMyPacketFromNet()\nPacketManager().process(pkt)\n\n\n# isolated test or isolated usage example\ndef test_control_packet():\n    p = ControlMessage()\n    PacketManager().my_func1(p)\n</code></pre>\n<p>So <strong>complexity is not spread in the code flow, but it is rendered in the code structure</strong>.</p>\n'}, {'answer_id': 37448954, 'author': 'dccsillag', 'author_id': 4803382, 'author_profile': 'https://Stackoverflow.com/users/4803382', 'pm_score': 2, 'selected': False, 'text': '<p>If you don\'t worry losing syntax highlight inside the case suites, you can do the following:</p>\n\n<pre><code>exec {\n    1: """\nprint (\'one\')\n""", \n    2: """\nprint (\'two\')\n""", \n    3: """\nprint (\'three\')\n""",\n}.get(value, """\nprint (\'None\')\n""")\n</code></pre>\n\n<p>Where <code>value</code> is the value. In C, this would be:</p>\n\n<pre><code>switch (value) {\n    case 1:\n        printf("one");\n        break;\n    case 2:\n        printf("two");\n        break;\n    case 3:\n        printf("three");\n        break;\n    default:\n        printf("None");\n        break;\n}\n</code></pre>\n\n<p>We can also create a helper function to do this:</p>\n\n<pre><code>def switch(value, cases, default):\n    exec cases.get(value, default)\n</code></pre>\n\n<p>So we can use it like this for the example with one, two and three:</p>\n\n<pre><code>switch(value, {\n    1: """\nprint (\'one\')\n    """, \n    2: """\nprint (\'two\')\n    """, \n    3: """\nprint (\'three\')\n    """,\n}, """\nprint (\'None\')\n""")\n</code></pre>\n'}, {'answer_id': 43536282, 'author': 'Tom', 'author_id': 3106539, 'author_profile': 'https://Stackoverflow.com/users/3106539', 'pm_score': 3, 'selected': False, 'text': '<p>Expanding on <a href="https://stackoverflow.com/a/60211/3106539">Greg Hewgill\'s answer</a> - We can encapsulate the dictionary-solution using a decorator:</p>\n\n<pre><code>def case(callable):\n    """switch-case decorator"""\n    class case_class(object):\n        def __init__(self, *args, **kwargs):\n            self.args = args\n            self.kwargs = kwargs\n\n        def do_call(self):\n            return callable(*self.args, **self.kwargs)\n\nreturn case_class\n\ndef switch(key, cases, default=None):\n    """switch-statement"""\n    ret = None\n    try:\n        ret = case[key].do_call()\n    except KeyError:\n        if default:\n            ret = default.do_call()\n    finally:\n        return ret\n</code></pre>\n\n<p>This can then be used with the <code>@case</code>-decorator</p>\n\n<pre><code>@case\ndef case_1(arg1):\n    print \'case_1: \', arg1\n\n@case\ndef case_2(arg1, arg2):\n    print \'case_2\'\n    return arg1, arg2\n\n@case\ndef default_case(arg1, arg2, arg3):\n    print \'default_case: \', arg1, arg2, arg3\n\nret = switch(somearg, {\n    1: case_1(\'somestring\'),\n    2: case_2(13, 42)\n}, default_case(123, \'astring\', 3.14))\n\nprint ret\n</code></pre>\n\n<p>The good news are that this has already been done in <a href="https://pypi.python.org/pypi/NeoPySwitch/0.2.0" rel="nofollow noreferrer">NeoPySwitch</a>-module. Simply install using pip:</p>\n\n<pre><code>pip install NeoPySwitch\n</code></pre>\n'}, {'answer_id': 44545063, 'author': 'Yster', 'author_id': 1317559, 'author_profile': 'https://Stackoverflow.com/users/1317559', 'pm_score': 4, 'selected': False, 'text': '<p>I was quite confused after reading the accepted answer, but this cleared it all up:</p>\n<pre><code>def numbers_to_strings(argument):\n    switcher = {\n        0: &quot;zero&quot;,\n        1: &quot;one&quot;,\n        2: &quot;two&quot;,\n    }\n    return switcher.get(argument, &quot;nothing&quot;)\n</code></pre>\n<p>This code is analogous to:</p>\n<pre><code>function(argument){\n    switch(argument) {\n        case 0:\n            return &quot;zero&quot;;\n        case 1:\n            return &quot;one&quot;;\n        case 2:\n            return &quot;two&quot;;\n        default:\n            return &quot;nothing&quot;;\n    }\n}\n</code></pre>\n<p>Check the <a href="https://www.pydanny.com/why-doesnt-python-have-switch-case.html" rel="noreferrer">Source</a> for more about dictionary mapping to functions.</p>\n'}, {'answer_id': 45530307, 'author': 'damirlj', 'author_id': 6424465, 'author_profile': 'https://Stackoverflow.com/users/6424465', 'pm_score': 0, 'selected': False, 'text': "<p>A switch statement is just syntactic sugar for if/elif/else.\nWhat any control statement is doing is delegating the job based on certain condition is being fulfilled - decision path. For wrapping that into a module and being able to call a job based on its unique id, one can use inheritance and the fact that any method in Python is virtual, to provide the derived class specific job implementation, as a specific &quot;case&quot; handler:</p>\n<pre><code>#!/usr/bin/python\n\nimport sys\n\nclass Case(object):\n    &quot;&quot;&quot;\n        Base class which specifies the interface for the &quot;case&quot; handler.\n        The all required arbitrary arguments inside &quot;execute&quot; method will be\n        provided through the derived class\n        specific constructor\n\n        @note in Python, all class methods are virtual\n    &quot;&quot;&quot;\n    def __init__(self, id):\n        self.id = id\n\n    def pair(self):\n        &quot;&quot;&quot;\n            Pairs the given id of the &quot;case&quot; with\n            the instance on which &quot;execute&quot; will be called\n        &quot;&quot;&quot;\n        return (self.id, self)\n\n    def execute(self): # Base class virtual method that needs to be overridden\n        pass\n\nclass Case1(Case):\n    def __init__(self, id, msg):\n        self.id = id\n        self.msg = msg\n    def execute(self): # Override the base class method\n        print(&quot;&lt;Case1&gt; id={}, message: \\&quot;{}\\&quot;&quot;.format(str(self.id), self.msg))\n\nclass Case2(Case):\n    def __init__(self, id, n):\n        self.id = id\n        self.n = n\n    def execute(self): # Override the base class method\n        print(&quot;&lt;Case2&gt; id={}, n={}.&quot;.format(str(self.id), str(self.n)))\n        print(&quot;\\n&quot;.join(map(str, range(self.n))))\n\n\nclass Switch(object):\n    &quot;&quot;&quot;\n        The class which delegates the jobs\n        based on the given job id\n    &quot;&quot;&quot;\n    def __init__(self, cases):\n        self.cases = cases # dictionary: time complexity for the access operation is 1\n    def resolve(self, id):\n\n        try:\n            cases[id].execute()\n        except KeyError as e:\n            print(&quot;Given id: {} is wrong!&quot;.format(str(id)))\n\n\n\nif __name__ == '__main__':\n\n    # Cases\n    cases=dict([Case1(0, &quot;switch&quot;).pair(), Case2(1, 5).pair()])\n\n    switch = Switch(cases)\n\n    # id will be dynamically specified\n    switch.resolve(0)\n    switch.resolve(1)\n    switch.resolve(2)\n</code></pre>\n"}, {'answer_id': 45683860, 'author': 'user2233949', 'author_id': 2233949, 'author_profile': 'https://Stackoverflow.com/users/2233949', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m just going to drop my two cents in here.  The reason there isn\'t a case/switch statement in Python is because Python follows the principle of &quot;there\'s only one right way to do something&quot;.   So obviously you could come up with various ways of recreating switch/case functionality, but the Pythonic way of accomplishing this is the if/elif construct. I.e.,</p>\n<pre><code>if something:\n    return &quot;first thing&quot;\nelif somethingelse:\n    return &quot;second thing&quot;\nelif yetanotherthing:\n    return &quot;third thing&quot;\nelse:\n    return &quot;default thing&quot;\n</code></pre>\n<p>I just felt <a href="https://pep8.org/" rel="noreferrer">PEP 8</a> deserved a nod here.  One of the beautiful things about Python is its simplicity and elegance.  That is largely derived from principles laid out in PEP 8, including &quot;There\'s only one right way to do something.&quot;</p>\n'}, {'answer_id': 45981619, 'author': 'The Nomadic Coder', 'author_id': 1933672, 'author_profile': 'https://Stackoverflow.com/users/1933672', 'pm_score': 2, 'selected': False, 'text': "<p>I've made a <em>switch case</em> implementation that doesn't quite use <em>ifs</em> externally (it still uses an <em>if</em> in the class).</p>\n<pre><code>class SwitchCase(object):\n    def __init__(self):\n        self._cases = dict()\n\n    def add_case(self,value, fn):\n        self._cases[value] = fn\n\n    def add_default_case(self,fn):\n        self._cases['default']  = fn\n\n    def switch_case(self,value):\n        if value in self._cases.keys():\n            return self._cases[value](value)\n        else:\n            return self._cases['default'](0)\n</code></pre>\n<p>Use it like this:</p>\n<pre><code>from switch_case import SwitchCase\nswitcher = SwitchCase()\nswitcher.add_case(1, lambda x:x+1)\nswitcher.add_case(2, lambda x:x+3)\nswitcher.add_default_case(lambda _:[1,2,3,4,5])\n\nprint switcher.switch_case(1) #2\nprint switcher.switch_case(2) #5\nprint switcher.switch_case(123) #[1, 2, 3, 4, 5]\n</code></pre>\n"}, {'answer_id': 47335084, 'author': 'nrp', 'author_id': 3426366, 'author_profile': 'https://Stackoverflow.com/users/3426366', 'pm_score': 1, 'selected': False, 'text': '<p>The following works for my situation when I need a simple switch-case to call a bunch of methods and not to just print some text. After playing with lambda and globals it hit me as the simplest option for me so far. Maybe it will help someone also:</p>\n\n<pre><code>def start():\n    print("Start")\n\ndef stop():\n    print("Stop")\n\ndef print_help():\n    print("Help")\n\ndef choose_action(arg):\n    return {\n        "start": start,\n        "stop": stop,\n        "help": print_help,\n    }.get(arg, print_help)\n\nargument = sys.argv[1].strip()\nchoose_action(argument)()  # calling a method from the given string\n</code></pre>\n'}, {'answer_id': 48013880, 'author': 'M T Head', 'author_id': 6710305, 'author_profile': 'https://Stackoverflow.com/users/6710305', 'pm_score': 1, 'selected': False, 'text': '<p>And another option:  </p>\n\n<pre><code>def fnc_MonthSwitch(int_Month): #### Define a function take in the month variable \n    str_Return ="Not Found"     #### Set Default Value \n    if int_Month==1:       str_Return = "Jan"   \n    if int_Month==2:       str_Return = "Feb"   \n    if int_Month==3:       str_Return = "Mar"   \n    return str_Return;          #### Return the month found  \nprint ("Month Test 3:  " + fnc_MonthSwitch( 3) )\nprint ("Month Test 14: " + fnc_MonthSwitch(14) )\n</code></pre>\n'}, {'answer_id': 48047214, 'author': 'ramazan polat', 'author_id': 234775, 'author_profile': 'https://Stackoverflow.com/users/234775', 'pm_score': 2, 'selected': False, 'text': '<p>Although there are already enough answers, I want to point a simpler and more powerful solution:</p>\n<pre><code>class Switch:\n    def __init__(self, switches):\n        self.switches = switches\n        self.between = len(switches[0]) == 3\n\n    def __call__(self, x):\n        for line in self.switches:\n            if self.between:\n                if line[0] &lt;= x &lt; line[1]:\n                    return line[2]\n            else:\n                if line[0] == x:\n                    return line[1]\n        return None\n\n\nif __name__ == \'__main__\':\n    between_table = [\n        (1, 4, \'between 1 and 4\'),\n        (4, 8, \'between 4 and 8\')\n    ]\n\n    switch_between = Switch(between_table)\n\n    print(\'Switch Between:\')\n    for i in range(0, 10):\n        if switch_between(i):\n            print(\'{} is {}\'.format(i, switch_between(i)))\n        else:\n            print(\'No match for {}\'.format(i))\n\n\n    equals_table = [\n        (1, \'One\'),\n        (2, \'Two\'),\n        (4, \'Four\'),\n        (5, \'Five\'),\n        (7, \'Seven\'),\n        (8, \'Eight\')\n    ]\n    print(\'Switch Equals:\')\n    switch_equals = Switch(equals_table)\n    for i in range(0, 10):\n        if switch_equals(i):\n            print(\'{} is {}\'.format(i, switch_equals(i)))\n        else:\n            print(\'No match for {}\'.format(i))\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>Switch Between:\nNo match for 0\n1 is between 1 and 4\n2 is between 1 and 4\n3 is between 1 and 4\n4 is between 4 and 8\n5 is between 4 and 8\n6 is between 4 and 8\n7 is between 4 and 8\nNo match for 8\nNo match for 9\n\nSwitch Equals:\nNo match for 0\n1 is One\n2 is Two\nNo match for 3\n4 is Four\n5 is Five\nNo match for 6\n7 is Seven\n8 is Eight\nNo match for 9\n</code></pre>\n'}, {'answer_id': 48614894, 'author': 'Solomon Ucko', 'author_id': 5445670, 'author_profile': 'https://Stackoverflow.com/users/5445670', 'pm_score': 3, 'selected': False, 'text': "<p>Simple, not tested; each condition is evaluated independently: there is no fall-through, but all cases are evaluated (although the expression to switch on is only evaluated once), unless there is a break statement. For example,</p>\n\n<pre><code>for case in [expression]:\n    if case == 1:\n        print(end='Was 1. ')\n\n    if case == 2:\n        print(end='Was 2. ')\n        break\n\n    if case in (1, 2):\n        print(end='Was 1 or 2. ')\n\n    print(end='Was something. ')\n</code></pre>\n\n<p>prints <code>Was 1. Was 1 or 2. Was something.</code> <sup>(Dammit! Why can't I have trailing whitespace in inline code blocks?)</sup> if <code>expression</code> evaluates to <code>1</code>, <code>Was 2.</code> if <code>expression</code> evaluates to <code>2</code>, or <code>Was something.</code> if <code>expression</code> evaluates to something else.</p>\n"}, {'answer_id': 48846312, 'author': 'Alejandro Quintanar', 'author_id': 1242902, 'author_profile': 'https://Stackoverflow.com/users/1242902', 'pm_score': 5, 'selected': False, 'text': "<p>Solution to run functions:</p>\n<pre><code>result = {\n    'case1':     foo1, \n    'case2':     foo2,\n    'case3':     foo3,\n}.get(option)(parameters_optional)\n</code></pre>\n<p>where foo1(), foo2() and foo3() are functions</p>\n<p><strong>Example 1</strong> (with parameters):</p>\n<pre><code>option = number['type']\nresult = {\n    'number':     value_of_int,  # result = value_of_int(number['value'])\n    'text':       value_of_text, # result = value_of_text(number['value'])\n    'binary':     value_of_bin,  # result = value_of_bin(number['value'])\n}.get(option)(value['value'])\n</code></pre>\n<p><strong>Example 2</strong> (no parameters):</p>\n<pre><code>option = number['type']\nresult = {\n    'number':     func_for_number, # result = func_for_number()\n    'text':       func_for_text,   # result = func_for_text()\n    'binary':     func_for_bin,    # result = func_for_bin()\n}.get(option)()\n</code></pre>\n<p><strong>Example 4</strong> (only values):</p>\n<pre><code>option = number['type']\nresult = {\n    'number':    lambda: 10,       # result = 10\n    'text':      lambda: 'ten',    # result = 'ten'\n    'binary':    lambda: 0b101111, # result = 47\n}.get(option)()\n</code></pre>\n"}, {'answer_id': 49367931, 'author': 'True', 'author_id': 4696698, 'author_profile': 'https://Stackoverflow.com/users/4696698', 'pm_score': 2, 'selected': False, 'text': '<p><em>I\'ve found the following answer from <a href="https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python" rel="nofollow noreferrer">Python documentation</a> most helpful:</em></p>\n<p>You can do this easily enough with a sequence of <code>if... elif... elif... else</code>. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.</p>\n<p>For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:</p>\n<pre><code>def function_1(...):\n    ...\n\nfunctions = {\'a\': function_1,\n             \'b\': function_2,\n             \'c\': self.method_1, ...}\n\nfunc = functions[value]\nfunc()\n</code></pre>\n<p>For calling methods on objects, you can simplify yet further by using the getattr() built-in to retrieve methods with a particular name:</p>\n<pre><code>def visit_a(self, ...):\n    ...\n...\n\ndef dispatch(self, value):\n    method_name = \'visit_\' + str(value)\n    method = getattr(self, method_name)\n    method()\n</code></pre>\n<p>It’s suggested that you use a prefix for the method names, such as <code>visit_</code> in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.</p>\n'}, {'answer_id': 49746559, 'author': 'abarnert', 'author_id': 908494, 'author_profile': 'https://Stackoverflow.com/users/908494', 'pm_score': 4, 'selected': False, 'text': '<p>Most of the answers here are pretty old, and especially the accepted ones, so it seems worth updating.</p>\n\n<p>First, the official <a href="https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python" rel="noreferrer">Python FAQ</a> covers this, and recommends the <code>elif</code> chain for simple cases and the <code>dict</code> for larger or more complex cases. It also suggests a set of <code>visit_</code> methods (a style used by many server frameworks) for some cases:</p>\n\n<pre><code>def dispatch(self, value):\n    method_name = \'visit_\' + str(value)\n    method = getattr(self, method_name)\n    method()\n</code></pre>\n\n<p>The FAQ also mentions <a href="https://www.python.org/dev/peps/pep-0275/" rel="noreferrer">PEP 275</a>, which was written to get an official once-and-for-all decision on adding C-style switch statements. But that PEP was actually deferred to Python 3, and it was only officially rejected as a separate proposal, <a href="https://www.python.org/dev/peps/pep-3103/" rel="noreferrer">PEP 3103</a>. The answer was, of course, no—but the two PEPs have links to additional information if you\'re interested in the reasons or the history.</p>\n\n<hr>\n\n<p>One thing that came up multiple times (and can be seen in PEP 275, even though it was cut out as an actual recommendation) is that if you\'re really bothered by having 8 lines of code to handle 4 cases, vs. the 6 lines you\'d have in C or Bash, you can always write this:</p>\n\n<pre><code>if x == 1: print(\'first\')\nelif x == 2: print(\'second\')\nelif x == 3: print(\'third\')\nelse: print(\'did not place\')\n</code></pre>\n\n<p>This isn\'t exactly encouraged by PEP 8, but it\'s readable and not too unidiomatic.</p>\n\n<hr>\n\n<p>Over the more than a decade since PEP 3103 was rejected, the issue of C-style case statements, or even the slightly more powerful version in Go, has been considered dead; whenever anyone brings it up on python-ideas or -dev, they\'re referred to the old decision.</p>\n\n<p>However, the idea of full ML-style pattern matching arises every few years, especially since languages like Swift and Rust have adopted it. The problem is that it\'s hard to get much use out of pattern matching without algebraic data types. While Guido has been sympathetic to the idea, nobody\'s come up with a proposal that fits into Python very well. (You can read <a href="http://stupidpythonideas.blogspot.com/2014/08/a-pattern-matching-case-statement-for.html" rel="noreferrer">my 2014 strawman</a> for an example.) This could change with <code>dataclass</code> in 3.7 and some sporadic proposals for a more powerful <code>enum</code> to handle sum types, or with various proposals for different kinds of statement-local bindings (like <a href="https://www.python.org/dev/peps/pep-3150/" rel="noreferrer">PEP 3150</a>, or the set of proposals currently being discussed on -ideas). But so far, it hasn\'t.</p>\n\n<p>There are also occasionally proposals for Perl 6-style matching, which is basically a mishmash of everything from <code>elif</code> to regex to single-dispatch type-switching.</p>\n'}, {'answer_id': 50686874, 'author': 'abarnert', 'author_id': 908494, 'author_profile': 'https://Stackoverflow.com/users/908494', 'pm_score': 2, 'selected': False, 'text': '<p>As a minor variation on <a href="https://stackoverflow.com/a/60215/908494">Mark Biek\'s answer</a>, for uncommon cases like <a href="https://stackoverflow.com/questions/50686700/">this duplicate</a> where the user has a bunch of function calls to delay with arguments to pack in (and it isn\'t worth building a bunch of functions out-of-line), instead of this:</p>\n\n<pre><code>d = {\n    "a1": lambda: a(1),\n    "a2": lambda: a(2),\n    "b": lambda: b("foo"),\n    "c": lambda: c(),\n    "z": lambda: z("bar", 25),\n    }\nreturn d[string]()\n</code></pre>\n\n<p>… you can do this:</p>\n\n<pre><code>d = {\n    "a1": (a, 1),\n    "a2": (a, 2),\n    "b": (b, "foo"),\n    "c": (c,)\n    "z": (z, "bar", 25),\n    }\nfunc, *args = d[string]\nreturn func(*args)\n</code></pre>\n\n<p>This is certainly shorter, but whether it\'s <em>more readable</em> is an open question…</p>\n\n<hr>\n\n<p>I think it might be more readable (although not briefer) to switch from <code>lambda</code> to <code>partial</code> for this particular use:</p>\n\n<pre><code>d = {\n    "a1": partial(a, 1),\n    "a2": partial(a, 2),\n    "b": partial(b, "foo"),\n    "c": c,\n    "z": partial(z, "bar", 25),\n    }\nreturn d[string]()\n</code></pre>\n\n<p>… which has the advantage of working nicely with keyword arguments as well:</p>\n\n<pre><code>d = {\n    "a1": partial(a, 1),\n    "a2": partial(a, 2),\n    "b": partial(b, "foo"),\n    "c": c,\n    "k": partial(k, key=int),\n    "z": partial(z, "bar", 25),\n    }\nreturn d[string]()\n</code></pre>\n'}, {'answer_id': 50688208, 'author': 'Alex Hall', 'author_id': 2482744, 'author_profile': 'https://Stackoverflow.com/users/2482744', 'pm_score': 2, 'selected': False, 'text': '<p>Similar to <a href="https://stackoverflow.com/a/50686874/2482744">this answer by abarnert</a>, here is a solution specifically for the use case of calling a single function for each \'case\' in the switch, while avoiding the <code>lambda</code> or <code>partial</code> for ultra-conciseness while still being able to handle keyword arguments:</p>\n\n<pre><code>class switch(object):\n    NO_DEFAULT = object()\n\n    def __init__(self, value, default=NO_DEFAULT):\n        self._value = value\n        self._result = default\n\n    def __call__(self, option, func, *args, **kwargs):\n        if self._value == option:\n            self._result = func(*args, **kwargs)\n        return self\n\n    def pick(self):\n        if self._result is switch.NO_DEFAULT:\n            raise ValueError(self._value)\n\n        return self._result\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>def add(a, b):\n    return a + b\n\ndef double(x):\n    return 2 * x\n\ndef foo(**kwargs):\n    return kwargs\n\nresult = (\n    switch(3)\n    (1, add, 7, 9)\n    (2, double, 5)\n    (3, foo, bar=0, spam=8)\n    (4, lambda: double(1 / 0))  # if evaluating arguments is not safe\n).pick()\n\nprint(result)\n</code></pre>\n\n<p>Note that this is chaining calls, i.e. <code>switch(3)(...)(...)(...)</code>. Don\'t put commas in between. It\'s also important to put it all in one expression, which is why I\'ve used extra parentheses around the main call for implicit line continuation.</p>\n\n<p>The above example will raise an error if you switch on a value that is not handled, e.g. <code>switch(5)(1, ...)(2, ...)(3, ...)</code>. You can provide a default value instead, e.g. <code>switch(5, default=-1)...</code> returns <code>-1</code>.</p>\n'}, {'answer_id': 50725576, 'author': 'Tony Suffolk 66', 'author_id': 3426606, 'author_profile': 'https://Stackoverflow.com/users/3426606', 'pm_score': 3, 'selected': False, 'text': "<p>A solution I tend to use which also makes use of dictionaries is:</p>\n<pre><code>def decision_time( key, *args, **kwargs):\n    def action1()\n        &quot;&quot;&quot;This function is a closure - and has access to all the arguments&quot;&quot;&quot;\n        pass\n    def action2()\n        &quot;&quot;&quot;This function is a closure - and has access to all the arguments&quot;&quot;&quot;\n        pass\n    def action3()\n        &quot;&quot;&quot;This function is a closure - and has access to all the arguments&quot;&quot;&quot;\n        pass\n\n   return {1:action1, 2:action2, 3:action3}.get(key,default)()\n</code></pre>\n<p>This has the advantage that it doesn't try to evaluate the functions every time, and you just have to ensure that the outer function gets all the information that the inner functions need.</p>\n"}, {'answer_id': 51811745, 'author': 'sudhir tataraju', 'author_id': 8520303, 'author_profile': 'https://Stackoverflow.com/users/8520303', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Easy to remember:</strong></p>\n\n<pre><code>while True:\n    try:\n        x = int(input("Enter a numerical input: "))\n    except:\n        print("Invalid input - please enter a Integer!");\n    if x==1:\n        print("good");\n    elif x==2:\n        print("bad");\n    elif x==3:\n        break\n    else:\n        print ("terrible");\n</code></pre>\n'}, {'answer_id': 52106213, 'author': 'Woody1193', 'author_id': 3121975, 'author_profile': 'https://Stackoverflow.com/users/3121975', 'pm_score': 3, 'selected': False, 'text': '<p>There have been a lot of answers so far that have said, "we don\'t have a switch in Python, do it this way". However, I would like to point out that the switch statement itself is an easily-abused construct that can and should be avoided in most cases because they promote lazy programming. Case in point:</p>\n\n<pre><code>def ToUpper(lcChar):\n    if (lcChar == \'a\' or lcChar == \'A\'):\n        return \'A\'\n    elif (lcChar == \'b\' or lcChar == \'B\'):\n        return \'B\'\n    ...\n    elif (lcChar == \'z\' or lcChar == \'Z\'):\n        return \'Z\'\n    else:\n        return None        # or something\n</code></pre>\n\n<p>Now, you <em>could</em> do this with a switch-statement (if Python offered one) but you\'d be wasting your time because there are methods that do this just fine. Or maybe, you have something less obvious:</p>\n\n<pre><code>def ConvertToReason(code):\n    if (code == 200):\n        return \'Okay\'\n    elif (code == 400):\n        return \'Bad Request\'\n    elif (code == 404):\n        return \'Not Found\'\n    else:\n        return None\n</code></pre>\n\n<p>However, this sort of operation can and should be handled with a dictionary because it will be faster, less complex, less prone to error and more compact.</p>\n\n<p>And the vast majority of "use cases" for switch statements will fall into one of these two cases; there\'s just very little reason to use one if you\'ve thought about your problem thoroughly.</p>\n\n<p>So, rather than asking "how do I switch in Python?", perhaps we should ask, "why do I want to switch in Python?" because that\'s often the more interesting question and will often expose flaws in the design of whatever you\'re building.</p>\n\n<p>Now, that isn\'t to say that switches should never be used either. State machines, lexers, parsers and automata all use them to some degree and, in general, when you start from a symmetrical input and go to an asymmetrical output they can be useful; you just need to make sure that you don\'t use the switch as a hammer because you see a bunch of nails in your code.</p>\n'}, {'answer_id': 52559968, 'author': 'Vikhyat Agarwal', 'author_id': 8663663, 'author_profile': 'https://Stackoverflow.com/users/8663663', 'pm_score': 4, 'selected': False, 'text': "<pre><code>def f(x):\n    dictionary = {'a':1, 'b':2, 'c':3}\n    return dictionary.get(x,'Not Found') \n##Returns the value for the letter x;returns 'Not Found' if x isn't a key in the dictionary\n</code></pre>\n"}, {'answer_id': 54549654, 'author': 'Felix Martinez', 'author_id': 10967582, 'author_profile': 'https://Stackoverflow.com/users/10967582', 'pm_score': 4, 'selected': False, 'text': '<p>You can use a dispatched dict:</p>\n<pre><code>#!/usr/bin/env python\n\n\ndef case1():\n    print(&quot;This is case 1&quot;)\n\ndef case2():\n    print(&quot;This is case 2&quot;)\n\ndef case3():\n    print(&quot;This is case 3&quot;)\n\n\ntoken_dict = {\n    &quot;case1&quot; : case1,\n    &quot;case2&quot; : case2,\n    &quot;case3&quot; : case3,\n}\n\n\ndef main():\n    cases = (&quot;case1&quot;, &quot;case3&quot;, &quot;case2&quot;, &quot;case1&quot;)\n    for case in cases:\n        token_dict[case]()\n\n\nif __name__ == \'__main__\':\n    main()\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>This is case 1\nThis is case 3\nThis is case 2\nThis is case 1\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/60208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4907/']