What is the Python equivalent for a case/switch statement?

Created by Prashant KumarLinked to 40.5m issues across 139 teams

tl;dr

Python does not have a built-in switch/case statement, but there are several ways to achieve the same result.

One way is to use the new pattern matching feature introduced in Python 3.10. This feature allows you to match a value to a specific pattern and execute a corresponding block of code. To use this feature, you need to define a function for each pattern and then use the match keyword to match the value to the pattern.

For example, if you wanted to match a status code to a corresponding message, you could do something like this:

def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" # If an exact match is not confirmed, this last case will be used if provided case _: return "Something's wrong with the internet"

If you are using a version of Python prior to 3.10, you can achieve the same result using a dictionary. To do this, you need to define a function for each pattern and then map the inputs to the corresponding function.

For example, if you wanted to match a number to a corresponding message, you could do something like this:

# define the function blocks def zero(): print "You typed zero. " def sqr(): print "n is a perfect square " def even(): print "n is an even number " def prime(): print "n is a prime number " # map the inputs to the function blocks options = {0 : zero, 1 : sqr, 4 : sqr, 9 : sqr, 2 : even, 3 : prime, 5 : prime
We use cookies to personalize content
run ads, and analyze traffic.