pythonpython-3.10structural-pattern-matching

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


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.


Solution

  • 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")