How to do an else (default) in match-case?

Viewed 5081

Python recently has released match-case in version 3.10. The question is how can we do a default case in Python? I can do if/elif but don't know how to do else. Below is the code:

x = "hello"
match x:
    case "hi":
        print(x)
    case "hey":
        print(x)
    default:
        print("not matched")

I added this default myself. I want to know the method to do this in Python.

3 Answers

You can define a default case in Python. For this you use a wild card (_). The following code demonstrates it:

x = "hello"
match x:
    case "hi":
        print(x)
    case "hey":
        print(x)
    case _:
        print("not matched")
for thing in [[1,2],[2,11],[12,14,13],[10],[10,20,30,40,50]]:
match thing:
    case [x]:
        print(f"single value: {x}")
    case [x,y]:
        print(f"two values: {x} and {y}")
    case [x,y,z]:
        print(f"three values: {x}, {y} and {z}")       
    case _: # change this in default 
        print("too many values")

If you want to read and get more understanding: https://towardsdatascience.com/pattern-matching-in-python-3-10-6124ff2079f0

Related