Prior to Python 3.10, only if-else statements were available. But Python 3.10 introduced the match and case statements, which provide the same functionality and similar syntax to traditional switch statements.
In the following example, we create a
day_of_week() function to demonstrate the use of the
case statements, Python's equivalent to the switch statement.
You can check out the full code on this Einblick canvas:
Comparing the syntax using the match and case statements, with the equivalent if-else statements, we can see that the match and case statements are a bit more concise, with less repetitive syntax.
Example using if-else
The function takes in a
day as a number. Based on the value of the number, the function will return a particular string.
def day_of_week_elif(day): if day == 0: return "Sunday" elif day == 1: return "Monday" elif day == 2: return "Tuesday" elif day == 3: return "Wednesday" elif day == 4: return "Thursday" elif day == 5: return "Friday" elif day == 6: return "Saturday" else: return "Something's wrong"
Note the similarities of the Python syntax with C syntax. Note the wildcard in the last case. The
_ wildcard will match for any other case, not enumerated in the prior cases.
def day_of_week(day): match day: case 0: return "Sunday" case 1: return "Monday" case 2: return "Tuesday" case 3: return "Wednesday" case 4: return "Thursday" case 5: return "Friday" case 6: return "Saturday" case _: # wildcard will always match return "Something's wrong"
In the official documentation of the Python 3.10 release, Python highlighted other ways to use the match statement, such as matching on a literal and a variable, using classes, and nested patterns.
Notes on switch statements
A switch statement is a control flow statement used to execute different code blocks based on different conditions. This may sound very similar to if-else statements, which are core to control flow. Typically, switch statements work by taking an expression and matching it with a particular case. If a match is found, the associated block of code is executed.
Einblick is an AI-native data science platform that provides data teams with an agile workflow to swiftly explore data, build predictive models, and deploy data apps. Founded in 2020, Einblick was developed based on six years of research at MIT and Brown University. Einblick is funded by Amplify Partners, Flybridge, Samsung Next, Dell Technologies Capital, and Intel Capital. For more information, please visit www.einblick.ai and follow us on LinkedIn and Twitter.