Python - Match/Case

python logo pixel art

Python `match-case` statement take an expression and compares it against a set of patterns. When a pattern matches the expression, the corresponding block of code is executed.


match-case statement
match expression:
    case pattern_1:
        # tasks...
    case pattern_2:
        # tasks...
    case _: # <- default
        # tasks...

In Python, the default case is represented by an underscore `_`.


fruit = 'papaya'
price = None

match fruit:
  case 'apple':
    print('apple: $0.14')
    price = 0.14
  case 'orange':
    print('orange: $0.17')
    price = 0.17
  case 'pear':
    print('pear: $0.09')
    price = 0.09
  case _:
     print('No price-label')

Case Patterns