HOLA
Welcome to Python Unleash'd 03
This is same as Switch Case, just Switch is replaced with Match, but with new super powers added.
It was introduced in Python 3.10.
It is similar to if-else block. When you do not want to extend if-else in multiple chain, use MATCH CASE
IMPORTANT POINTS TO REMEMBER
MATCH case differs from our classic switch not just because python and C++ are two programming langs but in python it has got some new powers as mentioned above
We do not have 'default' instead we have '_' for default case in the end
cases need not to be same data type, this is possible in C++ too btw, in the code below, we are able to implement OR in C++ switch statement indirectly, we are not actually using OR keyword but bringing its implementation. Also we are changing the type of case statement here. We can do same in python also.
We can ofcourse not put array here in cases since it already convert string/char to int when we give char/string value to menuChoice. I am figuring out how it will look if I have to work with array in switch statement, lets see this first.
int menuChoice = 1;
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 1:
case 'S':
cout<<"s for snake";
break;
default:
cout<<"invalid";
}
Found this link interesting for arrays in C++
BASIC MATCH CASE EXAMPLE PYTHON
sample_var = "string"
match sample_var:
case "string":
print("string here")
case 5:
print("five")
case _:
print("default")
I am missing chatgpt here
Switch case with OR in PYTHON
'|' is used for OR
sample_var = "string_second"
match sample_var:
case "string":
print("string here")
case 5 | "string_second":
print("five")
case _:
print("default")
NOW I AM JUST PLAYING WITH THIS CODE AND EXPLORING NEW THINGS
So here is another example, we are using if with MATCH CASE
sample_var = "lara"
list1 = ["ramesh", "suresh"]
name = "ramesh"
match sample_var:
case "lara" if name in list1:
print("lara has access to DB")
case "string":
print("string here")
case 5 | "string_second":
print("five")
case _:
print("default")
Looks interesting! right?
We can match dictionary, class even patterns, find more about this here
Thanks for reading!
Top comments (0)