Match-Case: switch-case Python style
Have you ever seen a line of code as pictured below, and just wanted to go to a pharmacy and buy some aspirin?
So, what is this abomination of pink, blue, orange and yellow? The code above is called an if-else statement. Its purpose is to check the value inside a variable based on a condition that has been set within the statement and executes (or not) certain lines of code depending if the condition has been met (True) or not (False). If-else statements have multiple uses in programming and can be chained together to navigate a menu, for example.
However, how long a menu proportionally affects how long a chain of if-else statement becomes. And a long nested if-else statement can often be hard to read and understand. Hence why some programming languages have switch-case statement.
Switch-case statement is similar to if-else statement but is easier to read and (slightly) faster to execute. Other reasons to use switch-case over if-else are easier debugging, easier maintenance, and easier value checking and handling. The switch-case statement is made of a switch and multiple case(s). The switch is responsible for testing the value in a variable assigned to it against the multiple cases inside it simultaneously, if the value matches with a case, then that the code block inside that case is executed, or if none of them match then a default case is executed instead. Many programming languages have implemented switch-case statement, and as of 3.10, Python has joined that group as well.
Get Benedict Emanuel Sutrisna’s stories in your inbox
Join Medium for free to get updates from this writer.
Meet match-case, Python’s very own switch-case statement.
Notice how the code above is easier to read than the previous block of code, which is the biggest advantage match-case has over if-else statement. Match-case also checks all conditions in every case simultaneously instead of checking every condition one by one, which makes match-case slightly faster than if-else. Though it may be insignificant, it would help shave off processing time for much larger code execution.
Python’s Match-Case works much like switch-case of other programming languages, with some improvements. Those familiar with switch-case may notice there is no ‘break’ line at the end of each case. Match-case can identify where its code block starts and end by the indentation of the code block it executes, thus it forgoes any ‘break’ command.
But wait, there’s more! You can add a ‘|’ (pipe operator) as an ‘or’ statement, allowing 2 or more values to run the same code, as seen in the picture below.
You can even combine it with if-in statement to check if the variable is in a collection variable as seen below.
There’s more but I’ll leave it to you to find the rest of the neat stuff Match-case has to offer. I hope this article help expand your python coding expertise. Thank you for Reading.





