20
Python 3.10 Structural Pattern Matching (Match Case)
After a wait of so many updates, Python has finally introduced a switch-case like structure in its latest 3.10 version. If we talk about other programming languages like, C++, Java, and JavaScript all these three popular programming languages support switch case statement, which is an alternative to write efficient and cleaner conditional statement.
Let's see an example of Switch Case statement in C++
#include <iostream>
using namespace std;
int main() {
int http = 200;
switch (http) {
case 200:
cout<<"OK";
break;
case 201:
cout<<"CREATED";
break;
case 202:
cout<<"ACCEPTED";
break;
case 400:
cout<<"BAD REQUEST";
break;
case 404:
cout<<"NOT FOUND";
break;
case 503:
cout<<"SERVICE UNAVAILABLE";
break;
default:
cout << "Error! HTTP Code is not valid";
break;
}
return 0;
}
OUTPUT
ok
The above code is very clean example of conditional statement. The switch case comes very handy when we have a conditional operation based on a single data object.
In Python 3.10, the core developer team of Python introduced a new conditional statement syntax Structural Pattern Matching, which is a similar syntax to the switch case statement present in the other programming languages.
Although Python contain if..else
and if...elif...else
statements to write conditional statements, but the all new Python Structural Pattern Matching provides a more elegant and legible way to write some conditional statement.
match subject:
case pattern1:
#case 1 code block
.....
....
...
case patternN:
#case N code block
-
match
is the keyword here. -
subject
is the value that need to be match. -
case
is also a keyword -
pattern
is the value that will be match withsubject
if any case pattern matches thematch
subject
that case code block will be executed.
http = 200
match http:
case 200:
print("OK")
case 201:
print("CREATED")
case 202:
print("ACCEPTED")
case 400:
print("BAD REQUEST")
case 404:
print("NOT FOUND")
case 503:
print("SERVICE UNAVAILABLE")
case _:
print("Error! HTTP Code is not valid")
OK
The new Python match case statement is an alternative of the switch case statement present in the other programming languages. Although the switch case statement provide an elegant way to write conditional statement, still for complex and multilayer conditional statement it is not a good option. It can only be used when the condition expression is a single value.
20