How to Use Switch Statements in Python

Get rid of cumbersome elif trees with pattern matching

How to Use Switch Statements in Python
Photo by elen aivali on Unsplash

Whenever I’m asked “why Python?” the answer undoubtedly revolves around its ease-of-use and human-logical style of syntax. Especially coming from other languages such as PHP, Java, or JavaScript, Python simply makes more sense.

Starting in version 3.10, one of my last grievances with Python — relative to other languages — is being addressed: the beloved switch statement.

In this article, we’ll introduce what switch statements are and how they are implemented in Python. Enjoy the tutorial and look forward to some refactoring!

What is a Switch Statement?

For the uninitiated, a switch statement is a programming decision structure where one of multiple branches is executed based on a comparison to a single value. Let’s take a look at a pseudo-code example:switch(day) {
   case "Monday":
      // office early
      break;
   case "Tuesday":
      // office
      break;
   case "Wednesday":
      // work from home
      break;
   case "Thursday":
      // gym then office
      break;
   case "Friday":
      // office half day
      break;
   default:
      // sleep in
      break;
}

The way we read this code block is that based on the value of day, the case that matches will be executed. The break keyword is to exit the switch statement entirely so it goes at the end of each case block.

Historically, there had been no syntactic equivalent in Python — we were stuck using long if/elif/else chains. Although functionally it would operate the same, and many argue that it offered greater flexibility, the reality is that it was cumbersome to write and did not feel “Pythonic”.

Using Pattern Matching in Python

Fortunately, we have been rescued starting in version 3.10 where pattern matching was introduced. While it isn’t called a “switch statement”, structured pattern matching is syntactically analogous and in many ways allows for the aforementioned flexibility.

First, let’s do a very simple example and translate our above switch statement.match day:
   case "Monday":
       print("Office Early")
   case "Tuesday":
       print("Office")
   case "Wednesday":
       print("Work From Home")
   case "Thursday":
       print("Gym then Office")
   case "Friday":
       print("Office Half Day")
   case _:
       print("Sleep In")

There are a few differences that should stick out immediately:

  • The block is called match and not switch.
  • There is no need for break statements thanks to Python’s indentation.
  • The default case is symbolized as an underscore (also it is called a wildcard match).

Now, where things get interesting is when we embrace the “pattern” in pattern matching and extend beyond simple strings. See, pattern matching goes far beyond a simple comparison. In actuality, pattern matching does two things:

  • Compares the structure of the subject (value after match) and each pattern (value after case).
  • Bind the values from the subject to the elements of the pattern.

Let’s take a look at an example where both are evident.words = input("Enter your three favorite words: ")match words.split():
   case []:
       print("You didn't enter anything")
   case [first]:
       print("You only entered one word")
   case [first, second]:
       print("You only entered two words")
   case [first, second, third]:
       print(first, second, third)
   case _:
       print("Too many words")

Here are some sample input/outputs from the above block.Enter your three favorite words:
You didn't enter anythingEnter your three favorite words: hello
You only entered one wordEnter your three favorite words: Hello World
You only entered two wordsEnter your three favorite words: I Love Python
I, Love, PythonEnter your three favorite words: Python is the best
Too many words

What’s happening here is the pattern matching is looking for a list (the result of the .split() method) which has a certain number of elements. Once it finds a pattern match with the correct number, then each value is bound to the variable(s) in that case.

Conclusion

Pattern matching is a real game changer in writing semantic, yet powerful Python. Just remember that the version number has to be 3.10+ or else you’ll be seeing an error.

What are some of exciting applications you can think of for pattern matching? Share your thoughts below in the comments and spread the word!

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe