Python Match · Exercises
Beginner

Python Match Exercises

4 exercises that build on the Python match Statement lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A match statement compares one value against a series of patterns, runs the first case that fits, and can pull pieces out of the value (such as the words of a command) at the same time. By the end you can write match/case with literal, wildcard, OR and capture patterns, add guards, match the shape of lists and tuples, parse a command string, and decide when if/elif is the better tool. You will practise: Weekend or weekday?; Which case runs?; Fix the text calculator; A tiny adventure interpreter.

0 / 4 completed

Python Match practice exercises

1. Weekend or weekday?

Write code Easy

Use a match statement on day to set the variable kind: it should be "weekend" for "Sat" or "Sun" (one case with |), and "weekday" for anything else (the wildcard _). Then print kind.

Try a few other days to see both outcomes, then set day back to "Sun" and press Check.

Your code
day = "Sun"

# use match day: ... to set kind, then print it

2. Which case runs?

Predict the output Medium

Read the code and type exactly what it will print. Work through the cases from top to bottom: does the pattern fit, and if it does, is the guard true? Then press Check to run it and compare.

Read this code
data = ["move", 5, 0]
match data:
    case ["move", x, y] if y > 0:
        print("up", x, y)
    case ["move", x, 0]:
        print("flat", x)
    case ["move", *rest]:
        print("other move", rest)
    case _:
        print("unknown")
print("done")

3. Fix the text calculator

Fix the bug Medium

calculate(line) should add two numbers for "add 2 3" (giving 5) and double a number for "double 4" (giving 8), but it returns "23" and "44". Fix it. Any other command should still return None.

A function is a named block of code: def introduces it, and return hands the answer back.

Your code
def calculate(line):
    match line.split():
        case ["add", a, b]:
            return a + b
        case ["double", n]:
            return n * 2
        case _:
            return None


print(calculate("add 2 3"))
print(calculate("double 4"))

4. A tiny adventure interpreter

Write code Hard

Write reply(command) using match command.split():. It returns a text:

command reply
quit Goodbye
go plus north, south, east or west Walking <direction>
go plus any other single word Cannot go <that word>
take followed by one or more items Took: and the items joined with ,
anything else (a bare take, a bare go, empty text, ...) Unknown command

The checker calls reply with many different commands, so cover all the rows.

Your code
def reply(command):
    # use match command.split(): with a case for each row of the table
    return "Unknown command"


print(reply("quit"))
print(reply("go north"))
print(reply("take lamp key"))

Next lessonPython for Loops

More Python match Statement examples · All Python exercises