35

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
farhan jatt
  • 509
  • 1
  • 8
  • 31

3 Answers3

49

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")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Prince Hamza
  • 1,090
  • 12
  • 21
3
match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

cf: https://docs.python.org/3.10/whatsnew/3.10.html#syntax-and-operations

Julien Sorin
  • 703
  • 2
  • 12
0
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

Tula Magar
  • 135
  • 10