Switch Case Statements

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn how to use the new Python Switch Case statement, also known as Structural Pattern Matching, introduced in Python 3.10. The Switch Case statement allows us to match patterns in an easier and more readable way compared to the traditional if-elif-else statements.

Achievements

  • Switch Case statements
  • if Statements

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/variables_data_types -.-> lab-94{{"`Switch Case Statements`"}} python/numeric_types -.-> lab-94{{"`Switch Case Statements`"}} python/strings -.-> lab-94{{"`Switch Case Statements`"}} python/conditional_statements -.-> lab-94{{"`Switch Case Statements`"}} python/lists -.-> lab-94{{"`Switch Case Statements`"}} python/standard_libraries -.-> lab-94{{"`Switch Case Statements`"}} python/data_collections -.-> lab-94{{"`Switch Case Statements`"}} python/build_in_functions -.-> lab-94{{"`Switch Case Statements`"}} end

Comparison with Python if Statements

Before we dive into the examples of the Python Switch Case statement, let's compare it with the traditional if-elif-else statements.

Consider the following example of matching HTTP response codes:

response_code = 200

if response_code == 200:
    print("OK")
elif response_code == 404:
    print("404 Not Found")
elif response_code == 500:
    print("Internal Server Error")

We can rewrite the same example using the Python Switch Case statement as follows:

response_code = 201

match response_code:
    case 200:
        print("OK")
    case 404:
        print("404 Not Found")
    case 500:
        print("Internal Server Error")

As you can see, the Python Switch Case statement is more concise and easier to read compared to the if-elif-else statements.

Here is the syntax for a switch case statement:

match term:
    case pattern-1:
        action-1
    case pattern-2:
        action-2
    case pattern-3:
        action-3
    case _:
        action-default

The term is the value that you want to match against the patterns. The pattern can be a single value, a tuple, a list, a builtin class, or a combination of these using the or operator (|). The _ is a catch-all pattern that matches any value.

Matching with the or Pattern

In this example, the pipe character (| or or) allows python to return the same response for two or more cases.

response_code = 502
match response_code:
    case 200 | 201:
        print("OK")
    case 500 | 502:
        print("Internal Server Error")

This will print "Internal Server Error" because the response_code is either 500 or 502.

We can use the underscore symbol _ to define a default case. Consider the following example:

response_code = 800

match response_code:
    case 200 or 201:
        print("OK")
    case 500 or 502:
        print("Internal Server Error")
    case _:
        print("Invalid Code")

In this example, the output will be "Invalid Code" because the value of response_code is not covered by any of the cases.

Matching Built-in Classes

We can also match patterns based on built-in classes. Consider the following example:

response_code = ["300"]

match response_code:
    case int():
        print('response_code is a number')
    case str():
        print('response_code is a string')
    case list():
        print('response_code is a list')
    case _:
        print('response_code is a unknown type')

This will print "response_code is a list" because the response_code is a list.

Summary

In this lab, we learned how to use the Python Switch Case statement introduced in Python 3.10. We compared it with the traditional if-elif-else statements and practiced several examples of matching single values, the or pattern, the length of an iterable, the underscore symbol for the default case, and built-in classes.

I hope you enjoyed this lab and learned something new!

Other Python Tutorials you may like