Did you know that there is a match-case function in python?

Joined
Jul 20, 2023
Messages
56
Reaction score
2
I dont know why but this is an extremely useful function yet extremely under documented/used in python help forums and websites. I mean w3schools.com has absolutely no mention of it. Many other programming languages use this only with the "switch-case" syntax and python implemented it in 3.10. When I found this out last week I immediately found places where I can use it and it looks so much cleaner if-elif statements and is so readable. However the lack of documentation makes it a bit hard to find some of its details. Its probably all in the actual python docs but I find those hard to understand sometimes so I like to reference difference websites and help forums. Heres a quick example if you want to get started using and Ill point out some of the hidden details.
Python:
print("""
1.) Do this
2.) Do that
3.) Exit
or press X to QUIT""")
user_selection = input("Enter a selection: ")

match user_selection.lower():
    case '1':
        print("Do this")
    case '2':
        print("Do that")
    case '3' | 'x':
        print("Thanks. See you later!")
        exit()
    case _:
        # This is the syntax for a non-match
        print("Invalid selection")

Note: One this I would call a downfall is that it doesnt recognize the logical operator keywords (and, or) but you can use the symbol shortcut (| for OR). I cant understand why they would allow that but not the actual keywords especially considering python tends to use the full keywords more so than other languages. Anyway hopefully they'll update that in a later version. And Im not sure about others like (IS, NOT, IN) and comparison operators (< , >, <=, >=) but I did notice somebody said in a different forum that you can use this syntax "case in ['x', 'y', 'z']" but that didnt work for me. It didnt let me use the in operator at all. I had to go with the | (or) rout. Maybe they've changed it from an earlier version. In any case its a great thing to know about if you ask me.
 
Last edited:
Joined
Jul 20, 2023
Messages
56
Reaction score
2
You can see that the embedded interpreter didnt highlight those keywords because it doesnt recognize it. So weird that this thing is so hidden.
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
Did you tried like this way too ...? ;)

[ working code on-line ]
Python:
def test(value):
    match value:
        case v if v in (1, 2):
            print(f"It's a tuple (1, 2) with elements {v}.")
        case v if v in [3, 4]:
            print(f"It's a list [3, 4] with elements {v}.")
        case _:
            print("Non-match")

test(2)
test(3)

[ working code on-line ]
Python:
def test(value):
    match value:
        case str(s):
            print(f"It's a string: {s}")
        case int(i):
            print(f"It's an integer: {i}")
        case float(v):
            print(f"It's an float: {v}")

test(2)
test('two')
test(3)
test(3.5)

[ working code on-line ]
Python:
def test(value):
    match value:
        case x if x > 0:
            print(f"Positive value: {x}")
        case 0:
            print("Zero")
        case x:
            print(f"Negative value: {x}")

test(2)
test(0)
test(-3)

[ working code on-line ]
Python:
def test(value):
    match value:
        case x if x > 0 and x % 2 == 0:
            print(f"Positive and even number: {x}")
        case x if x > 0:
            print(f"Positive number: {x}")
        case x:
            print(f"Non-positive number: {x}")

test(2)
test(1)
test(-3)
 
Joined
Jul 20, 2023
Messages
56
Reaction score
2
Did you tried like this way too ...? ;)

[ working code on-line ]
Python:
def test(value):
    match value:
        case v if v in (1, 2):
            print(f"It's a tuple (1, 2) with elements {v}.")
        case v if v in [3, 4]:
            print(f"It's a list [3, 4] with elements {v}.")
        case _:
            print("Non-match")

test(2)
test(3)

[ working code on-line ]
Python:
def test(value):
    match value:
        case str(s):
            print(f"It's a string: {s}")
        case int(i):
            print(f"It's an integer: {i}")
        case float(v):
            print(f"It's an float: {v}")

test(2)
test('two')
test(3)
test(3.5)

[ working code on-line ]
Python:
def test(value):
    match value:
        case x if x > 0:
            print(f"Positive value: {x}")
        case 0:
            print("Zero")
        case x:
            print(f"Negative value: {x}")

test(2)
test(0)
test(-3)

[ working code on-line ]
Python:
def test(value):
    match value:
        case x if x > 0 and x % 2 == 0:
            print(f"Positive and even number: {x}")
        case x if x > 0:
            print(f"Positive number: {x}")
        case x:
            print(f"Non-positive number: {x}")

test(2)
test(1)
test(-3)
Awesome examples. Honestly it actually has me a little confused. I cant find anything like that in the actual python docs. What im confused about is lets use examples:
Example 1:
match value:
case v if v in (1, 2):

Example 2:
match value:
case str(s):

in both examples were comparing against the variable 'value' right? So where do the viriables 'v' and 's' come from?
And also in example 2. Doesnt the str function create a string; not a boolean? Same with int and float?
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
So where do the viriables 'v' and 's' come from?
The variable v plays the role of a named variable within the pattern matching context in the match expression. It serves as a temporary variable that holds the value matched by a specific pattern in a given case of the matching.

+ test(2):
  • Call the test function with the argument 2.
  • In the match expression, it checks whether value matches any of the specified patterns.
  • In the first case (case v if v in (1, 2)), v becomes equal to 2 because the value of value is 2 and it matches the pattern (1, 2).
+ test(3):
  • Call the test function with the argument 3.
  • In the match expression, it again checks for matches with the specified patterns.
  • In the second case (case v if v in [3, 4]), v becomes equal to 3 because the value of value is 3 and it matches the pattern [3, 4].
In both cases, the variable v is a temporary variable used to store the value matched by a specific pattern. It's important to note that the scope of the variable v is limited to the case block, and it's not accessible outside of that specific case.

[ working code on-line ]
Python:
def test(value):
    match value:
        case value if value in (1, 2):
            print(f"It's a tuple (1, 2) with elements {value}.")
        case value if value in [3, 4]:
            print(f"It's a list [3, 4] with elements {value}.")
        case _:
            print("Non-match")

test(2)
test(3)

Doesnt the str function create a string; not a boolean? Same with int and float?
[ working code on-line ]
Python:
def test(value):
    match value:
        case value if isinstance(value, str):
            print(f"It's a string: {value}")
        case value if isinstance(value, int):
            print(f"It's an integer: {value}")
        case value if isinstance(value, float):
            print(f"It's an float: {value}")

test(2)
test('two')
test(3)
test(3.5)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top