Python - Match/Case
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 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
- case `OR`
num = 2 match num: case 2 | 3 | 5 | 7: print('prime!') case 1 | 4 | 6 | 8 | 9: print('no-prime!')
name = "John Doe" match name: case "Peter Parker" | "Marc Spector": print("Hello! You're a hero, right?") case "John Doe" | "Jane Doe": print("So... What is your real name?") case "Felipe Izolan": print("Hey! that's me!")
The `|` symbol means `OR`.
- case `if`
num = 3 match num: case num if num > 0: print('positive!') case num if num < 0: print('negative!') case _: print('zero')