Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Replacements for switch statement in Python?

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

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

Answer*

Cancel
6
  • 2
    Yes, for example if your variable option=="case2" your result=foo2() Commented Feb 20, 2018 at 21:27
  • and so and so forth. Commented Feb 20, 2018 at 21:41
  • Yes, I understand the purpose. But my concern is that if you only want foo2(), the foo1(), foo3(), and default() functions are all also going to run, meaning things could take a long time Commented Feb 21, 2018 at 17:57
  • 2
    omit the () inside the dictionary. use get(option)(). problem solved.
    – timgeb
    Commented Apr 10, 2018 at 6:00
  • 1
    Excellent the use of () is a grate solution, I made a gist to test it gist.github.com/aquintanar/01e9920d8341c5c6252d507669758fe5 Commented Apr 17, 2018 at 5:13