Match Statement (Python 3.10+)

Basic Match

  1. # match-case statement
  2. command = "start"
  3. match command:
  4. case "start":
  5. print("Starting...")
  6. case "stop":
  7. print("Stopping...")
  8. case _:
  9. print("Unknown")
  10. #ans: Starting...

Match with Or Pattern

  1. # multiple values
  2. status_code = 201
  3. match status_code:
  4. case 200 | 201:
  5. print("Success")
  6. case 404:
  7. print("Not Found")
  8. case _:
  9. print("Other")
  10. #ans: Success

Match with Default

  1. # underscore is wildcard
  2. x = 100
  3. match x:
  4. case 1:
  5. print("One")
  6. case 2:
  7. print("Two")
  8. case _:
  9. print("Default")
  10. #ans: Default

Match Without Default

  1. # no match, no output
  2. x = 5
  3. match x:
  4. case 1:
  5. print("One")
  6. case 2:
  7. print("Two")
  8. #ans: (nothing)

Exercises - Part 1

  1. # what prints?
  2. x = 2
  3. match x:
  4. case 1:
  5. print("One")
  6. case 2:
  7. print("Two")
  8. case _:
  9. print("Other")
  10. #ans: Two

Exercises - Part 2

  1. # default case?
  2. x = 100
  3. match x:
  4. case 1:
  5. print("One")
  6. case _:
  7. print("Default")
  8. #ans: Default

Exercises - Part 3

  1. # multiple values?
  2. x = 201
  3. match x:
  4. case 200 | 201:
  5. print("Success")
  6. case _:
  7. print("Other")
  8. #ans: Success

Exercises - Part 4

  1. # no match?
  2. x = 5
  3. match x:
  4. case 1:
  5. print("One")
  6. case 2:
  7. print("Two")
  8. #ans: nothing (no default, no match)

Exercises - Part 5

  1. # first match wins?
  2. x = 1
  3. match x:
  4. case 1:
  5. print("First")
  6. case 1:
  7. print("Second")
  8. #ans: First

Exercises - Part 6

  1. # match with string?
  2. cmd = "quit"
  3. match cmd:
  4. case "start":
  5. result = "Starting"
  6. case "quit":
  7. result = "Quitting"
  8. #ans: result is "Quitting"

Exercises - Part 7

  1. # wildcard position?
  2. x = 999
  3. match x:
  4. case _:
  5. print("Any")
  6. case 999:
  7. print("999")
  8. #ans: Any (wildcard matches first)

Exercises - Part 8

  1. # or pattern?
  2. x = 503
  3. match x:
  4. case 500 | 502 | 503:
  5. print("Server Error")
  6. #ans: Server Error

Exercises - Part 9

  1. # match None?
  2. x = None
  3. match x:
  4. case None:
  5. print("Is None")
  6. case _:
  7. print("Not None")
  8. #ans: Is None

Exercises - Part 10

  1. # match with guard? (advanced)
  2. x = 15
  3. match x:
  4. case n if n > 10:
  5. print("Big")
  6. case _:
  7. print("Small")
  8. #ans: Big

Google tag (gtag.js)