Skip to content
Foxipa
Code Completion 6 Challenges

Complete the Python Pattern Matching Code

Practice literal, sequence, mapping, guarded, value, and class match patterns.

Intermediate ~12 min read

Challenge 1

Use match to return the right label for status 200 or 404, with a wildcard fallback.

python Your answer
status = 404

match status:
    case 200:
        label = "OK"
    case :
        label = "Not found"
    case _:
        label = "Other"

print(label)

Press Ctrl⌘Enter to check your answer

Challenge 2

Capture the two coordinates from point.

python Your answer
point = (3, 8)

match point:
    case :
        print(x + y)
    case _:
        print("not a point")

Press Ctrl⌘Enter to check your answer

Challenge 3

Match the method and capture the path from the request mapping.

python Your answer
request = {"method": "GET", "path": "/home"}

match request:
    case :
        print(path)
    case _:
        print("other")

Press Ctrl⌘Enter to check your answer

Challenge 4

Add a guard so the first case handles non-negative even numbers.

python Your answer
number = 14

match number:
    case n :
        print("even")
    case _:
        print("other")

Press Ctrl⌘Enter to check your answer

Challenge 5

Match the existing State.STOP value. Do not use a bare capture name.

python Your answer
class State:
    START = "start"
    STOP = "stop"

command = "stop"

match command:
    case State.START:
        print("start")
    case :
        print("stop")
    case _:
        print("other")

Press Ctrl⌘Enter to check your answer

Challenge 6

Match the Point instance, capture both coordinates, and bind the full subject to matched_point.

python Your answer
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

point = Point(3, 8)

match point:
    case :
        print(x + y, matched_point is point)
    case _:
        print("not a point")

Press Ctrl⌘Enter to check your answer