537
votes

I'd like to know, is there a Python equivalent for the case statement such as the examples available on VB.net or C#?

2
As of Python 3.10 you can use Python's match ... case syntax: PEP 636. - iacob
Python 3.10.0 provides an official syntactic equivalent, making the submitted answers not the optimal solutions anymore! In this SO post I try to cover everything you might want to know about the match-case construct, including common pitfalls if you're coming from other languages. Of course, if you're not using Python 3.10.0 yet, the existing answers apply and are still valid for 2021. - fameman
I would've written this in an answer to this post, but unfortunately it doesn't allow for any more answers. But with more than one million views, I think this question needs at least a redirection to a more modern answer - especially when 3.10.0 becomes stable and Python beginners come across this post. - fameman

2 Answers

622
votes

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

210
votes

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".