Programming Languages - Python - python case statement

Python Match-Case Statement: Example & Alternatives

As a modern programming language, Python evolves constantly. It’s sometimes challenging, but necessary, to stay up-to-date on the latest innovations and features. One of the language’s most recent additions is the match-case statement. Introduced in Python 3.10, it allows you to evaluate an expression against a list of values. 

In this article, we’ll explain what a switch statement is in programming. Next, we’ll show you how to use the match-case statement with Python 3.10, and what you can do if you’re using an older version of Python.

What Is a Switch Statement?

As a programmer, you’ll often need to evaluate expressions against multiple values. Modern programming languages offer switch statements to do this. Here’s how a switch statement looks in pseudocode syntax:

switch expression # the expression has a certain value
case 1:           # we test the value
  do something    # the program performs an action depending on the value
      case 2:
  do something
      case 3:
  do something
      default:          # if none of the case statements is satisfied
        do something    # the program performs a default action

In the above code, expression gets compared against the values in each case clause. Once a matching case clause is found, the code inside that case clause is run. If there is no matching case clause for expression, the code under the default clause gets executed.

Let’s look at how to implement this in Python 3.10, using the new match-case statement.

How To Implement the Match-Case Statement in Python

Python 3.10 now offers a simple and effective way to test multiple values and perform conditional actions: the match-case statement. In case you’re familiar with C++, it works similarly to the switch case.

For our example, let’s say you’re building a program to check a computer’s processor. Based on the result, the program will let the gamer know if their processor is compatible with a certain video game. Here’s how our program would look:

# First, ask the player about their CPU
cpuModel = str.lower(input("Please enter your CPU model: "))

# The match statement evaluates the variable's value
match cpuModel:
case "celeron": # We test for different values and print different messages
        print ("Forget about it and play Minesweeper instead...")
case "core i3":
        print ("Good luck with that ;)")
case "core i5":
        print ("Yeah, you should be fine.")
case "core i7":
        print ("Have fun!")
case "core i9":
        print ("Our team designed nice loading screens… Too bad you won't see them...")
case _: # the underscore character is used as a catch-all.
        print ("Is that even a thing?")

The above code checks a few possible values for the cpuModel variable. If the CPU model the user enters doesn’t match our expected options, the final case statement prints an error message. Here’s a possible output:

Please enter your CPU model: core i9
Our teams designed nice loading screens... Too bad you won't see them...

The program worked as expected and printed out the corresponding statement after the player introduced their CPU model.

Alternatives to the Match-Case Statement

Python 3.10 is gradually being rolled out  in 2021. If you’re still using an older version of Python and are not able to update immediately, we’ve got you covered. Here are three alternatives to the match-case statement that you can use as workarounds.

If-Elif-Else Ladder

We can use the If-elif-else statement to simulate a match-case in Python. We’ll use the same game compatibility checker to better illustrate this. First, we can create a switch function. The program then calls it with certain input: 

# first, we create a function
def switch(case):

  # check if the argument matches the cases
  if case == "celeron":
  print ("Forget about it and play Minesweeper instead...")

  elif case =="core i3":
  print ("Good luck with that ;)")

  elif case == "core i5":
  print ("Yeah, you should be fine.")

  elif case == "core i7":
  print ("Have fun!")

  elif case == "core i9":
  print ("Our teams designed nice loading screens... too bad you won't see them...")

  else:
  print ("Is that even a thing?")

# ask for the user input
cpuModel = str.lower(input("Please enter your CPU model: "))

# call the function
switch(cpuModel)

We rely on the keyword elif here to replace the case dedicated keyword of Python 3.10. The else keyword is the catch-all or the equivalent of default in C++. The output shows that this code works fine:

Please enter your CPU model: celeron 
Forget about it and play Minesweeper instead...

The program works perfectly and provides the correct output based on the data entered.

Dictionary Mapping

Another possibility is to create a dictionary to store key-value pairs for testing and outputting. The code snippet below demonstrate how this works with a dictionary that stores the different possible cases:

# create a function with a dictionary
def switch(CPU):

  # definition of the dictionary
  cputester = {

  # case 1
  "celeron": "Forget about it and play Minesweeper instead...",

  # case 2
  "core i3": "Good luck with that ;)",

  # case 3
  "core i5": "Yeah, you should be fine.",

  # case 4
  "core i7": "Have fun!",

  # case 5
  "core i9": "Our teams designed nice loading screens... too bad you won't see them..."

  }

  # if not found, return message
  return cputester.get(CPU, "Is that even a thing?")

# ask the player about their CPU
cpuModel = str.lower(input("Please enter your CPU model: "))

# call and print the function
print(switch(cpuModel))

Here, the return keyword does the job of returning the generic message, in case the dictionary does not contain the required value.

Please enter your CPU model: core i3
Good luck with that ;)

Once again, the program returns a correct output.

Custom Class

Implementing a switch case statement using a class is slightly more complicated than the previous methods. For this reason, we’ll break our code down into smaller chunks and explain what each bit does.

Here’s the full code to implement a switch statement using a class:

class CPUswitch:
    def case_celeron(self):
        return "Forget about it and play Minesweeper instead..."
    def case_corei3(self):
        return "Good luck with that ;)"
    def case_corei5(self):
        return "Yeah, you should be fine."
    def case_corei7(self):
        return "Have fun!"
    def case_corei9(self):
        return "Our teams designed nice loading screens... too bad you won't see them"

    def switch(self, CPU):

      default = "Is that even a thing?"

      return getattr(self, 'case_' + str(CPU), lambda: default)()

# ask the player about their CPU
cpuModel = str.lower(input("Please enter your CPU model: "))# remove all spacescpuModel = cpuModel.replace(" ", "")

test=CPUswitch()
print(test.switch(cpuModel))

Now, let’s look at the example line-by-line.

To begin, we define a CPU switch class. We create a function to represent each CPU:

class CPUswitch:
def case_celeron(self):
    return "Forget about it and play Minesweeper instead..."
def case_corei3(self):
    return "Good luck with that ;)"
def case_corei5(self):
    return "Yeah, you should be fine."
def case_corei7(self):
    return "Have fun!"
def case_corei9(self):
    return "Our teams designed nice loading screens... too bad you won't see them"...

In this case, each of these functions returns a string, but you could perform any operation there.

Then we create the default function, which would return the string if the CPU model entered were not found: 

...def switch(self, CPU):

  default = "Is that even a thing?"

  return getattr(self, 'case_' + str(CPU), lambda: default)()...

The getattr() function takes three arguments. The first one is the object (self) in which it searches for the second argument (the case_+str(CPU) function). If it finds a function with the given name, it calls it.

The third argument, the lambda function, is the fallback: if the search for the matching function fails, the lambda tells the program what to do next. In our case, the program just calls the default function.

Once again, we ask the player to tell us their CPU model:

...# ask the player about their CPU
cpuModel = str.lower(input("Please enter your CPU model: "))# remove all spaces
cpuModel = cpuModel.replace(" ", "")...

Because we test the name of functions like case_corei5, we’re required to remove all spaces in our variable cpuModel, or Python will throw an error.

Finally, we create a test object out of our CPUswitch() class, call the switch method, and print the result:

...test=CPUswitch()
print(test.switch(cpuModel))...

The program output is as follows:

Please enter your CPU model: Core 2 Duo 
Is that even a thing?

The program worked as intended, although it required more code than the two previous examples. 


Together, these are three of the most common ways to implement a switch statement in Python. 

Learn To Code With Udacity

If you can update to Python 3.10, we recommend you use the brand new and efficient match-case statement, which we explained in this article. If you cannot use match-case, we covered three popular alternatives: a dictionary, an if-elif ladder, or a class.

Ready to continue your learning journey? 

Udacity’s Intro to Programming Nanodegree is a beginner-friendly program that will teach you the fundamentals of HTML, CSS, Python, and JavaScript. 

Enroll in our Intro to Programming Nanodegree today!