Python has met its Match

By Amanda Lee

‘Match-case’ is a function that was introduced in Python 3.10. Similar to if-elif-else statements, match-case statements are conditional statements used when matching certain values. However, they are more powerful and concise in pattern matching, improving readability of the code.

The match case statement is called with the keyword “match” followed by the expression to compare with. The expression can be any valid Python expression, e.g. a variable or a function call. Case statements are defined with a pattern to match, followed by an expression to evaluate to.

Consider this example of an if-else statement:

if moves == "R":
    column=c+1 
elif moves == "L":
    column=c-1
elif moves == "U":
    row=r-1
elif moves == "D":
    row=r+1 

To improve readability, a match-case statement can be used instead:

match moves:
    case "R":
        column=c+1 
    case "L":
        column=c-1
    case "U":
        row=r-1
    case "D":
        row=r+1 

Similar to else in Python, or CASE OF in pseudocode, there is an OTHERWISE option, called using ‘_’:

match moves:
    case "R":
        column=c+1 
    case "L":
        column=c-1
    case "U":
        row=r-1
    case "D":
        row=r+1 
    case _:
        n=n+1

If there are multiple patterns evaluating to the same expression, a vertical bar ‘|’ can be used:

match moves:
    case "R"|"r":
        column=c+1 
    case "L":
        column=c-1
    case "U":
        row=r-1
    case "D":
        row=r+1 
    case _:
        n=n+1