Python Switch Case—Comprehensive Guide

Switch Case in Python
Image design by Elias Ervast

Python switch-case statements are here! And they are actually called match-case statements.

This means you can soon replace this type of if-else mess:

With a more compact match-case statement:

In some situations, the latter approach is better. It can make the code more readable and less repetitive.

Notice that this becomes available in Python 3.10, which will be released early in October 2021.

In this guide, you learn everything you need to know about Python match-case statements.

The Problem with If-Else in General

Speaking of any programming language, if-else statements are not always the most effective way to make comparisons. This is true when the if-else statements are repetitive.

To see an example, let’s write a pseudocode script that checks the day of the week using if-else statements:

In this piece of code, there is a lot of repetition.

Each else-if check repeats day == “something”.

However, it is clear we are referring to day in each comparison. So it would be great if we did not need to repeat day == “something”.

This gives rise to a neat solution called the switch-case statement.

The Solution—Switch Case Statements

The switch-case statement combines if-else statements into a single pattern-matching structure.

Using switch-case, you specify the value you are interested in and specify patterns (cases) for each possible outcome. The code then tries to match the value with the patterns.

Using a switch-case statement helps you avoid repetition and makes the code clean.

Here is a pseudocode example of replacing the above if-else mess with switch-case:

This looks way cleaner.

The switch-case is seen in popular programming languages, such as C++.

Python 3.10 also supports switch-case statements. But they go with a different name—match-case statements.

Match Case Statement—Python’s Version of Switch Case

Python versions of 3.10+ start supporting the switch-case statement. Notice how in Python, it is called match-case, not switch-case.

The match-case statement is also known as structural pattern matching.

The problem match-case solves is described in the previous chapter. In short, it replaces repetitive if-else statements with a compact pattern-matching structure.

Match Case in Python

The match-case statement follows this syntax:

Here:

  • The match element means “match the element with the following patterns”
  • Then each case pattern statement compares the element with the specified pattern. This can for example be a string or number.
  • If a pattern matches with the element, the corresponding block of code gets executed. After that, the match-case statement is exited.

Example

Let’s implement the weekday pseudocode example in Python.

The regular if-else approach would look like this:

But with Python 3.10 match-case statement, you can prettify the code quite a bit:

By the way, you can (with multiple expressions you should) break the expressions to separate lines:

Now you have a basic understanding on what is structural pattern matching in Python. Let’s then jump into different pattern types you can match with.

Match Case Pattern Types

There are different types of patterns you can match with.

The most notable ones are:

  • Literal patterns
  • Capture patterns
  • Wildcard patterns
  • Constant value patterns
  • Sequence patterns

Let’s go through each in detail.

Literal Patterns

The most basic use case for match cases is matching with literal patterns. The literal you can match with can be a:

  • Number
  • String
  • None
  • True
  • False

A good example of literal pattern matching is the weekday example. In this example, we match a string literal with a variable day:

Capture Patterns

You can use the match-case statement to store (capture) a matched value to a variable.

This is best demonstrated with an example.

For example, let’s create a function greet() that greets a person if a name is specified.

This match-case statement does two things (as highlighted in the comments):

  • Checks if the name is None. If it is, the default greeting is printed.
  • Checks if the name matches with something else than None. If it does, that name is stored into some_name. This name is then greeted.

Wildcard Pattern

When using match-case, you can use a wildcard pattern to match without binding. This is the “else” block of a match-case statement.

The wildcard pattern matches with a value that no other case is matching with.

To create a wildcard pattern, use the underscore _.

For example, let’s match for a result of a coin flip:

Output:

Must be 0 or 1.

Here the wildcard case matches with anything else than 0 or 1.

Another use case for the wildcard is if you don’t care about the value of the match. This is useful when you want to make sure there is the value (or a group of values), regardless of what that value is.

For example, let’s check the dimension of a tuple that represents a location without caring about the coordinate values:

Output:

2D location found

As you can see, this match-case only cares about the number of elements found.

Constant Value Patterns—Enumerations and Match Case

You can use enumeration items as patterns in a match-case statement.

In case you are unfamiliar with enumerations, see this article.

To demonstrate how an enumeration and match-case statement can be used:

  • Let’s create a Direction enumeration that represents the four main directions in the compass.
  • Let’s also create a function handle_directions() that takes a direction as an input. This function matches the direction with one of the directions from the enumeration and reacts accordingly.

Here is the code:

Now you can call handle_directions() this way for example:

handle_directions(Direction.NORTH)

You could replace the above script with a much simpler one. But this demonstrates how you can use enumerations and match-case.

The reason why you may want to do this is that you don’t want to use so-called mystic strings in your code. For more details on what this means, see this article.

Sequence Patterns

You can unpack the values of a sequence in pattern matching.

If you don’t know what unpacking is, it means pulling the values of a sequence into separate variables.

Here is an example:

You can use unpacking in pattern matching.

For example, let’s check if a location is a 1D, 2D, or 3D point. In addition, let’s store the coordinate values into separate variables and print them out.

Output:

2D location found: (1, 3)

The code matches location with a tuple of one, two, or three elements. The coordinate values are then unpacked to separate variables.

If you have more values, but you care about the first three, you can use the * operator. This accounts for “the rest of the elements”.

For instance, let’s say you have a tuple location that represents coordinates. In addition, it can store additional elements. To catch the extra items, let’s use the * operator:

Output:

3D location found: (1, 3, 2)
Also, there was some extra data: ['a', 'b', 'c']

Now *names captures all “the rest” of the elements in the location tuple—no matter how many extra elements there are.

Now you know the basic pattern types you can match against.

Let’s finally take a look at how to combine patterns.

Combining Patterns in Match Case

It is possible to compare patterns in a match-case statement.

To do this, use the logical or operator |. This checks if at least one pattern matches the value.

For example, let’s match days based on if they are weekends or not:

Output:

Work

Conclusion

In programming, the switch-case statement is a replacement for repetitive if-else statements.

This feature will be unlocked in Python 3.10 in early Oct 2021. In Python, it goes with the name of match-case statement.

Here is an example of a match-case statement:

The match-case statement matches a value with a group of patterns. If there is a match, a piece of code is executed.

Match-case works similar to if-else statements. The main difference is you don’t need to repeat the name of the compared item.

Thanks for reading. I hope you find it useful.

Happy coding!

Become a Top Coder

Did you like this article?

Become a member at Medium.com to read top stories by experts in the field.

Disclaimer: By joining via the provided link, I earn a small commission at no extra cost for you :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Artturi Jalli

Artturi Jalli

I built a blog from 0 to 500k+ monthly visits in 16 months without SEO.