Switch Case in Python using the match statement

Article updated on Saturday, March 16, 2024.

Switch Case in Python using the match statement

How to use the match-case? Why prefer it over if statements? What is this instruction for? Discover all about the Python version of switch-case!

The match-case statements arrived with Python version 3.10 and PEP 634. It’s the equivalent of switch-case in other programming languages. This “Structural Pattern Matching” instruction allows checking if a variable matches one of the defined values.

The match-case looks like this in Python:

match value:
  case pattern_1:
    expression_1
  case pattern_2:
    expression_2
  case pattern_3:
    expression_3
  case _:
    default_expression

Before Python 3.10, one had to use if conditions to test if the content of a variable matched a pattern.

def switch(day):
  if day == 1:
    return 'Monday'
  elif day == 2:
    return 'Tuesday'
  elif day == 3:
    return 'Wednesday'
  elif day == 4:
    return 'Thursday'
  elif day == 5:
    return 'Friday'
  elif day == 6:
    return 'Saturday'
  elif day == 7:
    return 'Sunday'
  else:
    return 'Not a day of the week'

Now with the match statement, we can avoid the if-elif-else instructions for a more readable code.

match day:
  case 1:
    return 'Monday'
  case 2:
    return 'Tuesday'
  case 3:
    return 'Wednesday'
  case 4:
    return 'Thursday'
  case 5:
    return 'Friday'
  case 6:
    return 'Saturday'
  case 7:
    return 'Sunday'
  case _:
    return 'Not a day of the week'

How to implement a switch-case in Python?

If you’re using a version earlier than Python 3.10, it can be useful to create your own switch/match case instruction. This can be done by creating a function that takes a parameter and tests it against different patterns.

def switch(value):
  if value == pattern_1:
    expression_1
  elif value == pattern_2:
    expression_2
  elif value == pattern_3:
    expression_3
  else:
    default_expression
  • def is the keyword that creates a function in Python
  • switch is the function’s name
  • value is the function’s parameter
  • if, elif, and else are condition keywords
  • pattern_x are the values against which we compare our value variable
  • expression_x is the code that will be executed or returned if the comparison is true
  • default_expression is what will be executed if value did not match any pattern

How to check the status code of a request in Python?

You can easily check the status of an HTTP response with a match case in Python.

Take the example below, where we have a response code (response_code) that we test against multiple values.

This code will allow us to provide better messages to our users.

response_code = 200

match response_code:
  case 200:
    print("All went well 🎉")
  case 300 | 301 | 302:
    print("You will be redirected 😅")
  case 400 | 404:
    print("This page doesn't seem to exist 😭")
  case 500:
    print("Oops, something went wrong 🤯")

Our simple request that succeeded with a code 200 will display All went well 🎉 on the standard output.

This example is very simple; you should add better error handling with more error codes and more customization.

Also, note the use of the | operator when you want to test against multiple values!

How to check the integrity of a structure in Python?

It’s possible to check the structure of an object in Python using the switch case (match-case) instruction.

Take a list of n elements; we will print a different sentence depending on the structure of this list.

list = ['one', 'two', 'three', 'four', 'five', 'six']

match list:
  case [a]:
    print(f'Only one value: {a}')
  case [a, b]:
    print(f'Two values: {a} and {b}')
  case [a, b, c]:
    print(f'Three values: {a}, {b}, and {c}')
  case [a, b, c, d]:
    print(f'Four values: {a}, {b}, {c}, and {d}')
  case [a, b, c, d, *rest]:
    print(f'Four values {a}, {b}, {c}, {d} but also {", ".join(rest)}')

This will display the string Four values one, two, three, four but also five, six on the standard output.

How to handle commands as arguments in Python?

You can also use the pipe operator (|) to test one or more elements of the list.

Imagine a script that takes commands to add or subtract a number from a total number.

In Python, you can use values passed as arguments from the console using the sys.argv variable.

sys.argv[0] is the file name, so we start at sys.argv[1].

import sys

match sys.argv[1:]:
  case ['add', value_to_add, starting_value]:
    print(f'We added {value_to_add} to {starting_value}, resulting in {int(starting_value) + int(value_to_add)}')
  case ['subtract', value_to_subtract, starting_value]:
    print(f'We subtracted {value_to_subtract} from {starting_value}, resulting in {int(starting_value) - int(value_to_subtract)}')
  case ['help']:
    print('Add a help message explaining to the user how to use the script')

If you run the Python script like this python FILE_NAME.py add 5 4, you’ll get We added 5 to 4, resulting in 9 on the standard output.


Thomas Collart

Hey, I'm Thomas 👋 Here, you'll find articles about tech, and what I think about the world. I've been coding for 20+ years, built many projects including Startups. Check my About/Start here page to know more :).