Python case Keyword
Example
Use case
inside a match
statement to define patterns:
command = "start"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case _:
print("Unknown command")
Try it Yourself »
Definition and Usage
The case
keyword is used in combination with the match
keyword to define a pattern to match against a subject value.
When a case
pattern matches, the corresponding block of code is executed. The first matching case wins.
match
/case
is Python's structural pattern matching feature, introduced in Python 3.10.
More Examples
Example
Use an OR-pattern to match multiple literal values in one case:
ext = "jpg"
match ext:
case "jpg" | "jpeg":
print("JPEG image")
case "png":
print("PNG image")
case _:
print("Other format")
Try it Yourself »
Example
Use a variable capture and a guard to refine the match:
n = 7
match n:
case x if x % 2 == 0:
print("Even:", x)
case x:
print("Odd:", x)
Try it Yourself »
Related Pages
The match
keyword.
Read more about pattern matching in our Python match Tutorial.