Using the Match Case Statement in Python
In this post I describe the match case statement in Python, and how to use it.
I try to spend 30 minutes to an hour each day on learning to code, usually working my way through the Meta frontend and backend courses in Coursera. Then I practice what I’ve learned, and write about it here to crystallise the learning. December went pretty well, January didn’t really got going, till today.
In python and other programming languages it is really easy to find yourself writing increasingly convoluted if / elif / else blocks dealing with all the permutations of what you are trying to achieve. Match case deals with that by simplifying the arguments that you write and the amount of code needed to write them.
Before getting going though, it is worth point out that this functionality was introduced to Python in 3.10 - so you are not going to see it in legacy code, and you may need to upgrade your interpreter if the installed version is more than a couple of years old.
At the beginning of the match statement you identify the value that you wish to test, in the example below I will be testing against the variable your_club.lower(). This saves declaring the variable in each test, as I would need to do in writing an if / elif / else block.
Having identified the value to test against in the match statement, the corresponding case statements identify what should happen if that value matches. Statements are simplified further by the and/or operators & and |which provide for additional conditionality in a very straightforward way. For example, in the code below if your_club.lower() is either "blackburn’ or ‘blackburn rovers’ the value ‘Deadwood’ will be returned.
your_club = input("Please enter the name of the team you support: ")
statement = your_club + " play at: "
match your_club.lower():
case "accrington":
print(statement + "the Wham Stadium")
case "blackburn" | "blackburn rovers:
print(statement + "Deadwood")
case "burnley":
print(statement + "Turf Moor")
case _:
print("Sorry, " + your_club + " is not in our database yet.")
Trinket
Hopefully if you found this wee article you found it useful, if you did please let me know using the kudos button below, or by commenting through micro.blog or mastodon.

Leave a reply
Have your own site? Link to this page and send a webmention — it'll appear here. Otherwise, use the form.