SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Python Programming and Python Code Tutorials for Programmers


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.

mycolor = 'Blue'
match mycolor.lower():
   case 'blue':
      print('Blue sea')
   case 'green':
      print('Green valley')
   case 'yellow':
      print('Yellow sun')
   case _:
      print('could not guess')
Sample Match Case Statement in Python Code

The output of the above Python code execution can be seen below

sample Python Case statement code

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

mycolor = 'Blue'
if mycolor.lower() == 'blue':
   print('Blue sea')
elif mycolor.lower() == 'green':
   print('Green valley')
elif mycolor.lower() == 'yellow':
   print('Yellow sun')
else:
   print('could not guess')
Sample Match Case Statement in Python Code

As seen below, the execution of the above Python code is producing the same output

Python code using IF ELIF ELSE instead of CASE or switch

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.



Python Tutorials


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.