Python Match Case Statement and Case-Switch Equivalent
With Python 3.10 developers will be able to use MATCH CASE statements within their programs. One of the enhancements that is new in Python 3.10 is the announcement of structural pattern matching with Match Case statements.
Up to 3.10 Python did not have a switch or a case statement. Although programmers can adapt their code from CASE or SWITCH statements which exists in many other programming languages by using IF - ELIF - ELIF - ELSE statements, using MATCH CASE will improve code readability.
In this Python tutorial, I will show how to use MATCH CASE with sample Python codes as well as display work-around of MATCH CASE with IF ELIF and ELSE for environments prior to Python 3.10
Python programmers can download and install Python 3.10 from python.org to test the alpha release of next Python runtime.
The below Python script can help developers to evaluate the new CASE statement.
Although not a perfect use case, I hope it introduces the major syntax and application logic for all.
Please note that the last CASE matching criteria is _ which is for all other options or for all other remaining cases.
So it is an ELSE case in application.
The output of the above Python code execution can be seen below
If you are not running your application on Python 3.10 version and have a previous release of Python runtime, you can apply the common workaround case where IF control statement is used with multiple ELIF and ELSE
Here is how the above sample can be implemented on Python 3.7
As seen below, the execution of the above Python code is producing the same output
Of course the above samples can be used for different requirements and matching different data types. I hope Python developers will find MATCH CASE statement handy for their development tasks.