The match
and case
keywords in Python 3.10 and later versions provide a new way to implement conditional statements similar to switch-case statements in other programming languages.
Here is a complete tutorial on how to use the match and case keywords in Python 3.10 and later versions:
Syntax
Python
match expression:
case value1:
# code to execute if expression == value1
case value2:
# code to execute if expression == value2
...
case _:
# code to execute if expression does not match any of the case values
- The
expression
in thematch
statement can be any value, including integers, strings, and objects. - The
case
keyword is used to specify the possible values of the expression, followed by a colon. - The code to execute for each case is written after the colon.
- The
case _
is used to specify a block of code that will execute if none of the cases match the expression.
Example
Python
x = 2
match x:
case 1:
print("x is 1")
case 2:
print("x is 2")
case 3:
print("x is 3")
case _:
print("x is not 1, 2 or 3")
In this example, x
is equal to 2
, so the code inside case 2
will be executed, and x is 2
will be printed.
Tips
- You can use more than one case to execute the same block of code.
- The
case _
block is optional, but it's a good practice to include it in case of unexpected values. - The
match
andcase
keywords are new features in Python 3.10 and later versions and are not supported in previous versions of Python.
In conclusion, the match
and case
keywords in Python 3.10 and later versions provide a new way to implement conditional statements similar to switch-case statements in other programming languages. It makes your code more readable and easy to maintain. It's a new feature, so make sure that you are running the appropriate version of Python before using it.