Publish AI, ML & data-science insights to a global community of data professionals.

How to Write Switch Statements in Python

Understanding how to write switch statements in Python using pattern matching or dictionaries

Programming

Photo by Steve Johnson on Unsplash
Photo by Steve Johnson on Unsplash

Introduction

The typical way to deal with multiway branching in programming languages is the if-else clause. When we need to code numerous scenarios, an alternative is the so-called switch or case statement that is supported by most modern languages.

For Python versions < 3.10 however, there was no such statement that is able to select a specified action based on the value of a particular variable. Instead, we usually had to write a statement incorporating multiple if-else statements or even create a dictionary that we could then be indexed based on a specific variable value.

In today’s short guide we will demonstrate how to write switch or case statements in the form of if-else series or dictionaries. Additionally, we will demonstrate the new pattern matching feature that was introduced as of Python 3.10 version.


Writing if-else statements

Let’s assume that we have a variable named choice that takes some string values and based on the value of the variable will then print a float number.

Using a series of if-else statements that would look like the code snippet shown below:

if choice == 'optionA':
    print(1.25)
elif choice == 'optionB':
    print(2.25)
elif choice == 'optionC':
    print(1.75)
elif choice == 'optionD':
    print(2.5)
else:
    print(3.25)

In traditional if-else statements we enclose the default option (i.e. the option that should be selected when the value of the variable does not match any of the available options) in the else clause.


Writing a switch statement using a dictionary

Another possibility (if you are using Python < 3.10) are dictionaries since they can be easily and efficiently indexed. For instance, we could create a mapping where our options correspond to the keys of the dictionaries and the values to the desired outcome or action.

choices = {
    'optionA': 1.25,
    'optionB': 2.25,
    'optionC': 1.75,
    'optionD': 2.5,
}

Finally, we can pick the desired choice by providing the corresponding key:

choice = 'optionA'
print(choices[choice])

Now we somehow need to deal with the case where our choice is not included in the specified dictionary. If we try to provide a non-existent key, we will get back a KeyError. There are essentially two ways we can handle this scenario.

The first option requires the use of get() method when selecting the value from the dictionary that also allows us to specify the default value when the key is not found. For example,

>>> choice = 'optionE'
>>> print(choices.get(choice, 3.25)
3.25

Alternatively, we can use the try statement which is a general way for handling defaults by catching the KeyError.

choice = 'optionE'
try:
    print(choices[choice])
except KeyError:
    print(3.25)

Pattern Matching in Python ≥ 3.10

Python 3.10 introduced the new structural pattern matching (PEP 634):

Structural pattern matching has been added in the form of a match statement and case statements of patterns with associated actions. Patterns consist of sequences, mappings, primitive data types as well as class instances. Pattern matching enables programs to extract information from complex data types, branch on the structure of data, and apply specific actions based on different forms of data.

Source – Python Docs

Therefore, we can now simplify our code as below:

choice:
    case 'optionA':
        print(1.25)
    case 'optionB':
        print(2.25)
    case 'optionC':
        print(1.75)
    case 'optionD':
        print(2.5)
    case _:
        print(3.25)

Note that we can even combine several choices in a single case or pattern using | (‘or’) operator as demonstrated below:

case 'optionA' | 'optionB':
    print(1.25)

Final Thoughts

In today’s article we discussed a few alternative ways for implementing switch statements in Python given that prior to version 3.10 there’s no built-in construct like many other programming languages.

Therefore, you could instead write traditional if-else statements or even initialise a dictionary where the keys correspond to the conditions that would have been used in if/else if statements and values correspond to the desired value when that particular condition (key) holds.

Additionally, we showcased how to use the new pattern matching switch statement that was recently introduced in Python 3.10.


Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.

Join Medium with my referral link – Giorgos Myrianthous


You may also like

Augmented Assignments in Python


How to Perform Real-Time Speech Recognition with Python


apply() vs map() vs applymap() in Pandas


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.

Write for TDS

Related Articles