Python: Match Operator
Many programming languages, in addition to the if
conditional statement, include a switch
construct. With the release of Python 3.10, a similar functionality was introduced called the match
operator. In this lesson, we will explore this operator.
The match
operator is a specialized version of if
, designed for specific situations. For instance, it is useful when dealing with a chain of if else
statements that check for equality:
if status == 'processing':
# Do something for 'processing'
elif status == 'paid':
# Do something for 'paid'
elif status == 'new':
# Do something for 'new'
else:
# Do something for everything else
The distinguishing feature of this composite check is that each branch corresponds to a check on the variable status
. The match
operator allows us to express this code more succinctly:
match status:
case 'processing': # status == 'processing'
# Do something for 'processing'
case 'paid': # status == 'paid'
# Do something for 'paid'
case 'new': # status == 'new'
# Do something for 'new'
case _: # else
# Do something for everything else
In terms of elements, the match
operator is a complex construct. It consists of the following:
- The outer description, which includes the keyword
match
. This represents the variable whose values will determine the behavior chosen bymatch
. case
constructs inside, where we describe the behavior for different values of the considered variable. Eachcase
corresponds to anif
in the example above. Thecase _
is a special situation that corresponds to theelse
branch in conditional statements. Specifyingcase _
is optional, similar to usingelse
.
Inside match
, only the syntax shown above is permitted. In other words, we can use case
. However, inside each case
, the situation is different. Here, we can execute any arbitrary code:
match count:
case 1:
# Do something useful
case 2:
# Do something useful
case _:
# Do something
Sometimes, the result obtained inside a case
leads to the end of the function containing the match
. In such cases, it needs to be returned somehow. There are two ways to handle this:
The first approach involves creating a variable before the match
, filling it in case
, and then returning the value of that variable at the end:
def count_items(count):
# Declare a variable
result = ''
# Fill it
match count:
case 1:
result = 'one'
case 2:
result = 'two'
case _:
result = None
# Return it
return result
The second and simpler approach is to directly return from the function while working with case
:
def count_items(count):
match count:
case 1:
return 'one'
case 2:
return 'two'
case _:
return None
While the match
operator is not strictly necessary in Python, it offers the advantage of better expressing the programmer's intent when checking specific variable values. Though the code may grow slightly in size, it becomes more readable compared to using elif
blocks.
Instructions
Implement the function get_number_explanation()
, which takes a number as input and returns an explanation for that number. If there is no explanation for the number, return just a number
. Explanations are available only for the following numbers:
- 666 - devil number
- 42 - answer for everything
- 7 - prime number
Function call examples:
get_number_explanation(8) # just a number
get_number_explanation(666) # devil number
get_number_explanation(42) # answer for everything
get_number_explanation(7) # prime number
The exercise doesn't pass checking. What to do? 😶
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
In my environment the code works, but not here 🤨
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
My code is different from the teacher's one 🤔
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
I've read the lessons but nothing is clear 🙄
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.