Switch Case in Python

A switch case is a flow control statement used in programming languages. In this article, we will discuss the switch case in Python.

The syntax of switch statements in programming languages like C++, C, Java, etc.

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

How does it work?

  • The switch expression is evaluated once
  • The value of each case is evaluated, if there is a match associated code will be executed
  • If none of the cases matched it will execute the default case

Python 3.10 and Switch case

Python 3.10 introduced a match-case statement that provides switch-like functionality. The match-case statement is based on the PEP 634 specification.

The syntax of match case :

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

This structural pattern matching has a match statement and case statements. A match statement takes an expression and compares its value to successive patterns.

The match case works as follows:

  • It evaluates the subject in the match statement( using data with type and shape).
  • Compares the subject with each pattern from top to bottom until a match is confirmed.
  • Executes the action associated with the matched case.
  • If no match exists, and a wildcard _ exists then the action associated will be executed.
  • If no match exists, the behavior is a no-op.

Example

In this example, the status is the subject and it is checked against possible cases 400,404,418. If the status does not match with any of the cases it will execute the wildcard _ case.

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"


message = http_error(400)
print(f"HTTP status : {message}")

Output

HTTP status : Bad request

The match case without wildcard _ case

In this example, we will not use the wildcard _ case then if there is no match the behavior will be a no-op(no operation).

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"

message = http_error(500)
print(f"HTTP status : {message}")

Output

HTTP status : None

It is possible to combine several cases by using | ,” or”.

case 401 | 403 | 404:
    return "Not allowed"

So what about older versions of Python?

Older versions of Python don’t have the switch statement. To use the switch case in older versions of Python the official reply is

You can do this easily enough with a sequence of if... elif... elif... else.

Final words

In conclusion, the Python language is evolving the new match-case pattern matching is good and feature-rich.