Python match-case construct
In Python, since version 3.10, there is a special construct match-case, which is used to select one value from a range of values. Its syntax is:
match varuable:
case 'value1':
'''
here is the code that will be executed
if the variable has the value 1
'''
case 'value2'
'''
here is the code that will be executed
if the variable has the value 2
'''
case _:
'''
here is the code that will be executed
if the value does not match anything
'''
Let us have a variable tst:
tst = 'a'
Let's write down in the condition the different options that the variable can take:
match tst:
case 'a':
print('a')
case 'b':
print('b')
case _:
print('tst is unknown')
Also, using the operator |, you can specify a selection of the required values in each variant:
match tst:
case 'a' | 'c':
print('a or c')
case 'b' | 'd':
print('b or d')
case _:
print('tst is unknown')
Let the variable num store one of the numbers: 1, 2, 3 or 4, containing the season number. Print the name of the season contained in the number.
Let the variable num store a month number from 1 to 12. Print the name of the season corresponding to this month.