Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 12

Pattern Matching: match and case

This lesson goes with Episode 12 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

12.1 Why match exists

In Chapter 11 you wrote a menu as an if/elif chain:

choice = "2"
if choice == "1":
    print("Your balance is 250 dollars.")
elif choice == "2":
    print("How much would you like to deposit?")
elif choice == "3":
    print("Goodbye.")
else:
    print("Please choose 1, 2 or 3.")

Output

How much would you like to deposit?

It works, but look at how much repeats: choice == appears on every line. The real idea, "look at choice and pick the matching case", is buried. The match statement says that idea directly:

choice = "2"
match choice:
    case "1":
        print("Your balance is 250 dollars.")
    case "2":
        print("How much would you like to deposit?")
    case "3":
        print("Goodbye.")
    case _:
        print("Please choose 1, 2 or 3.")

Output

How much would you like to deposit?

match was added in Python 3.10, in 2021, so you will see plenty of older code and tutorials that never use it. Its full name is structural pattern matching, and by the end of the chapter you will see why "structural" is in the name.

Practice 12.1

Multiple choice

In which version of Python was the match statement added?

Choose one answer

12.2 The parts of a match

  match choice:            ◄── the SUBJECT: the value being examined
      case "1":            ◄── a PATTERN, followed by a colon
          print("...")     ◄── the block for that case
      case "2":
          print("...")
      case _:              ◄── the WILDCARD: matches anything
          print("...")
  • After match comes the subject: any expression. Python works it out once.
  • Each case holds a pattern: a description of what the subject might look like.
  • Under each case is a block, indented one more level. So the blocks sit eight spaces in.

How it runs

Python tries the patterns from the top, one at a time. At the first pattern that fits, it runs that block and then leaves the whole match. This is the same "first one wins" rule as an elif chain.

  • At most one block runs. There is no "falling through" into the next case, as there is in some other languages. You never need anything like a break at the end of a case.
  • If no pattern fits, nothing happens. No block runs and there is no error. The program just continues after the match.
colour = "purple"
match colour:
    case "red":
        print("Stop")
    case "green":
        print("Go")
print("After the match")

Output

After the match

The wildcard _

A single underscore is the wildcard pattern. It fits absolutely anything, so it is the else of a match. Put it last. Python insists on this, because anything after it could never be reached:

colour = "red"
match colour:
    case _:
        print("Something else")
    case "red":
        print("Stop")

Output

  File "lights.py", line 3
SyntaxError: wildcard makes remaining patterns unreachable

Quick check

What does this print for size = "L"? And for size = "XL"?

match size: with cases "S" → print(10), "M" → print(12), "L" → print(14)

Show the answer

Answer: for "L" it prints 14. For "XL" it prints nothing: no case fits and there is no wildcard.

Practice 12.2

Fill in the blank

Fill in the pattern that fits anything and throws the value away, so that an unknown size gets a message.

size = "XL"
match size:
    case "S":
        print(10)
    case "M":
        print(12)
    case :
        print("No such size")

The finished program prints:

Target

No such size

Predict the output

What does it print?

drink = "juice"
match drink:
    case "tea":
        print("Hot")
    case "water":
        print("Cold")
print("Done")

Multiple choice

What does this program print?

number = 2
match number:
    case 1:
        print("one")
    case 2:
        print("two")
    case _:
        print("other")
Choose one answer

Put the lines in order

Put the lines in order. The indentation of each line is already correct. The program asks for a size and prints one message.

With the reply S, the program in the right order prints:

Target

Small
  1. case "S":
  2. case _:
  3. print("Small")
  4. size = input("Size: ")
  5. print("Other size")
  6. match size:

12.3 Matching exact values

The patterns so far are literal patterns: actual values written in the code. A literal pattern fits when the subject is equal to it. Strings and numbers both work:

status = 404
match status:
    case 200:
        print("OK")
    case 404:
        print("Not found")
    case 500:
        print("Server error")
    case _:
        print("Something else")

Output

Not found

Three details:

  • The comparison is the same as ==. So case 1: also fits 1.0, and it even fits True, because True == 1 (Chapter 5).
  • None, True and False are compared by identity (is), which is the right way to test for them.
  • The types must make sense together. If the subject is the string "404" from input(), then case 404: will never fit. This is the same trap as comparing input with a number in an if.

Several values in one case: |

A vertical bar between patterns means "or". The case fits if any of the alternatives fits:

day = "Sun"
match day:
    case "Sat" | "Sun":
        print("Weekend")
    case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
        print("Weekday")
    case _:
        print("Not a day I know")

Output

Weekend

This is called an or-pattern. Notice that it uses the | symbol, not the word or. Inside a pattern, or is not allowed.

Practice 12.3

Predict the output

What does it print?

count = True
match count:
    case 0:
        print("zero")
    case 1:
        print("one")
    case _:
        print("other")

Fill in the blank

Fill in one pattern that fits the reply y and also the reply yes.

reply = input("Continue? ")
match reply:
    case :
        print("Continuing")
    case _:
        print("Stopping")

With the reply yes, the finished program prints:

Target

Continuing

Fix the bug

This program should print Lobby for floor 0 and Offices for floors 1 and 2. It prints No such floor for every reply. Fix it.

With the reply 0, the program prints the lines below. Your program must print exactly these lines.

Example run

Lobby

12.4 Capturing: a pattern can give you a value

So far match has only been a neater elif. Here is the first thing it can do that a comparison cannot.

A name used as a pattern fits anything, just like _. But unlike _, it also assigns the subject to that name, so the block can use it:

command = "dance"
match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case other:
        print(f"I do not know the command '{other}'.")

Output

I do not know the command 'dance'.

case other: fitted, and other became a variable holding "dance". This is called a capture pattern. On its own it is only a small convenience (you could have used command). It becomes powerful when it is part of a bigger pattern, as you will see in section 12.6.

The difference between the two catch-alls:

Pattern Fits Keeps the value?
_ anything no, it is thrown away
other (any name) anything yes, in the variable other

The trap: a name never compares

Because a bare name captures, it cannot be used to compare against a variable. This is the mistake nearly everyone makes with match:

RED = "red"
colour = "blue"
match colour:
    case RED:
        print("The colour is red!")
print("RED is now:", RED)

Output

The colour is red!
RED is now: blue

Two things went wrong at once. The colour is blue, but the program says red. And the "constant" RED has been overwritten with "blue".

Why? case RED: does not mean "if colour equals the value of RED". It means "capture whatever the subject is and call it RED". A capture always fits.

When there are more cases after it, Python at least catches the problem, for the same reason as with the wildcard:

RED = "red"
GREEN = "green"
colour = "blue"
match colour:
    case RED:
        print("Stop")
    case GREEN:
        print("Go")

Output

  File "lights.py", line 5
SyntaxError: name capture 'RED' makes remaining patterns unreachable

How to compare with a value that is stored in a variable:

  • Write the literal in the pattern: case "red":.
  • Or use a guard, from the next section: case c if c == RED:.
  • Or use a name with a dot in it, such as Colour.RED. A dotted name is looked up and compared, not captured. That is how constants grouped in an enum are used with match → Chapter 49.

Practice 12.4

Multiple choice

What does this program print?

command = "jump"
match command:
    case "start":
        print("Starting")
    case other:
        print("Unknown:", other)
Choose one answer

Predict the output

Read the case line with care. What does it print?

LIMIT = 10
speed = 80
match speed:
    case LIMIT:
        print("Limit reached")
print(LIMIT)

12.5 Guards: a pattern plus a condition

Literal patterns test for exact values. What about "any number below zero"? A pattern cannot say "less than", but you can attach an ordinary condition to a case with if. This is called a guard:

temperature = -4
match temperature:
    case 0:
        print("Exactly freezing")
    case t if t < 0:
        print(f"{t} is below freezing")
    case t if t < 15:
        print(f"{t} is cold")
    case t:
        print(f"{t} is mild or warm")

Output

-4 is below freezing

Read case t if t < 0: in two steps:

  1. The pattern t fits anything and captures the subject as t.
  2. Then the guard t < 0 is checked. Only if it is true does the case count as a match. If it is false, Python moves on to the next case.

A guard can use any expression at all, including and, or, method calls and other variables.

For a chain that is nothing but ranges, like this one, a plain if/elif is honestly just as clear. Guards earn their place when they are combined with the structural patterns coming next.

Quick check

In the temperature example, what is printed for 0, for 10 and for 30?

Show the answer

Answer: Exactly freezing; 10 is cold; 30 is mild or warm. For 0 the first case wins, so the guards are never checked.

Practice 12.5

Predict the output

What does it print?

n = 15
match n:
    case k if k > 20:
        print("large")
    case k if k % 5 == 0:
        print("multiple of five")
    case k if k > 10:
        print("medium")
    case _:
        print("small")

Fill in the blank

Fill in the guard so that every price below 10 is Cheap.

price = int(input("Price: "))
match price:
    case 0:
        print("Free")
    case p if :
        print("Cheap")
    case p:
        print("Costly")

With the reply 7, the finished program prints:

Target

Cheap

Put the lines in order

Put the lines in order. The indentation of each line is already correct. A speed above 120 is too fast.

With the reply 140, the program in the right order prints:

Target

140 is too fast
  1. print(s, "is too fast")
  2. case s if s > 120:
  3. print(s, "is fine")
  4. match speed:
  5. case s:
  6. speed = int(input("Speed: "))

Fix the bug

The program should print Correct! only when the guess is the secret word, and the last line should always show plum. Now every guess is Correct!. Fix it and keep the variable SECRET.

With the reply kiwi, the program prints the lines below. Your program must print exactly these lines.

Example run

The secret was plum

Write code

Parcel weight. Ask for the weight of a parcel in whole kilograms. Print exactly one of these lines: Nothing to send for 0, Not a real weight for a number below 0, Small parcel for 1 to 5, and Large parcel for more than 5. Use match with one literal pattern and guards.

With the reply 0, the program prints the lines below. Your program must print exactly these lines.

Example run

Nothing to send

12.6 Matching the shape of data

This is the "structural" part. A pattern can describe not just a value but the structure of a value: how many parts it has, what some of the parts are, and names for the others.

A command with several words

Chapter 9 showed that split() turns a line of text into a list of words → Chapter 25. A pattern in square brackets matches a list with exactly that many items:

command = "go north"
match command.split():
    case ["look"]:
        print("You see a small room.")
    case ["go", direction]:
        print(f"You walk {direction}.")
    case ["take", item]:
        print(f"You pick up the {item}.")
    case _:
        print("I do not understand.")

Output

You walk north.

Look closely at case ["go", direction]:. That one pattern makes three checks and one assignment:

  1. Is the subject a sequence?
  2. Does it have exactly two items?
  3. Is the first item equal to "go"? (a literal: compared)
  4. Whatever the second item is, call it direction. (a name: captured)

Here is the same logic written with if:

command = "go north"
words = command.split()
if len(words) == 1 and words[0] == "look":
    print("You see a small room.")
elif len(words) == 2 and words[0] == "go":
    direction = words[1]
    print(f"You walk {direction}.")
elif len(words) == 2 and words[0] == "take":
    item = words[1]
    print(f"You pick up the {item}.")
else:
    print("I do not understand.")

Output

You walk north.

It gives the same result, with length checks, index numbers and separate assignments. The match version shows the shape you are looking for, and the names appear exactly where the values are. This is the kind of job match was designed for.

Because the length is part of the pattern, wrong shapes are rejected without any extra code. "go" alone (one word) and "go north quickly" (three words) both fall through to the wildcard.

"And the rest": the star

A name with a star in front captures all the remaining items, however many there are, as a list:

command = "say hello to everyone"
match command.split():
    case ["say", *words]:
        print("You say:", " ".join(words))
    case []:
        print("You said nothing.")

Output

You say: hello to everyone

*words took ["hello", "to", "everyone"]. It can also take zero items, so "say" alone would fit with words as an empty list. Only one starred name is allowed per pattern. Use *_ to accept extra items without keeping them.

The pattern [] fits only an empty list, which is what split() gives for an empty or all-spaces line.

Options inside a pattern

Or-patterns work inside a sequence. To give the whole alternative a name, add as:

command = "go up"
match command.split():
    case ["go", ("north" | "south" | "east" | "west") as direction]:
        print(f"You walk {direction}.")
    case ["go", ("up" | "down") as direction]:
        print(f"You climb {direction}.")
    case ["go", _]:
        print("You cannot go that way.")

Output

You climb up.

The third case uses _ in the second position: "go, followed by one thing I do not care about". The order of the cases matters as always. Put that general case first and it would swallow every go command.

Matching several values at once

To make a decision that depends on two values together, put them in a pair. Round brackets with a comma make a tuple → Chapter 30, and a tuple pattern matches it position by position:

x = 0
y = 7
match (x, y):
    case (0, 0):
        print("At the origin")
    case (0, _):
        print("On the y-axis")
    case (_, 0):
        print("On the x-axis")
    case _:
        print("Somewhere else")

Output

On the y-axis

Compare this with the chain of and conditions in the quadrant exercise of Chapter 11. The table-like layout makes it easy to check that every combination is covered.

A famous exercise, FizzBuzz, becomes a table too. For a number, say Fizz if it divides by 3, Buzz if by 5, FizzBuzz if by both, and otherwise the number itself:

number = 15
match (number % 3 == 0, number % 5 == 0):
    case (True, True):
        print("FizzBuzz")
    case (True, False):
        print("Fizz")
    case (False, True):
        print("Buzz")
    case _:
        print(number)

Output

FizzBuzz

Quick check

With the first command example in this section, what is printed for "take lamp", for "look" and for "take"?

Show the answer

Answer: You pick up the lamp.; You see a small room.; and I do not understand. because ["take"] has only one item and the pattern needs two.

Practice 12.6

Put the lines in order

Put the lines in order. The indentation of each line is already correct. The program understands a command of two words that begins with go.

With the reply go home, the program in the right order prints:

Target

Going to home
  1. print(f"Going to {place}")
  2. line = input("> ")
  3. print("Unknown command")
  4. match line.split():
  5. case ["go", place]:
  6. case _:

Predict the output

What does it print?

line = "sum 4 5 6"
match line.split():
    case ["sum"]:
        print("nothing to sum")
    case ["sum", first, *rest]:
        print(first, len(rest))

Multiple choice

The subject is a string of two characters. What does this program print?

code = "ok"
match code:
    case [first, second]:
        print("two parts")
    case _:
        print("no match")
Choose one answer

Fill in the blank

Fill in the blank so that the second case fits every point whose second number is 0. The first number can be anything, and the block does not need it.

x = 4
y = 0
match (x, y):
    case (0, 0):
        print("origin")
    case (, 0):
        print("on the x-axis")
    case _:
        print("elsewhere")

The finished program prints:

Target

on the x-axis

Predict the output

What does it print?

year = 1900
match (year % 4 == 0, year % 100 == 0):
    case (True, False):
        print("leap year")
    case (True, True):
        print("check 400")
    case _:
        print("common year")

Fix the bug

go north and go south should print You walk on.. Any other direction should print You cannot go that way.. Now every go command gets the second message. Fix it.

With the reply go north, the program prints the lines below. Your program must print exactly these lines.

Example run

You walk on.

12.7 Matching by type

A pattern can ask "what kind of value is this?" Write the type's name followed by brackets:

value = 3.5
match value:
    case int():
        print("a whole number")
    case float():
        print("a decimal number")
    case str():
        print("some text")
    case None:
        print("nothing at all")
    case _:
        print("something else")

Output

a decimal number

int() here does not build a number, as it does in ordinary code. Inside a pattern it means "any value whose type is int". The brackets are essential. Without them, case int: would be a bare name, and as section 12.4 warned, that captures everything and overwrites the name int.

To test the type and keep the value, put a name inside the brackets, or use as:

value = "hello"
match value:
    case int(number):
        print(f"The number {number}, doubled is {number * 2}")
    case str(text):
        print(f"The text '{text}' has {len(text)} characters")

Output

The text 'hello' has 5 characters

One surprise: True is an int

Chapter 5 explained that bool is a kind of int. So case int(): also fits True and False:

value = True
match value:
    case int():
        print("an integer")
    case bool():
        print("a Boolean")

Output

an integer

To tell them apart, test for bool() first. As with an elif chain: most specific case first.

Shape and type together

Patterns nest, so type patterns can sit inside sequence patterns, with a guard on top. Here is a small "understand anything" example:

data = ["move", 3, 4]
match data:
    case ["move", int(dx), int(dy)] if dx == 0 and dy == 0:
        print("Not moving at all")
    case ["move", int(dx), int(dy)]:
        print(f"Move {dx} across and {dy} up")
    case ["move", *_]:
        print("move needs two whole numbers")

Output

Move 3 across and 4 up

The second case reads almost like a sentence: a list of three things: the word "move", then an integer I will call dx, then an integer I will call dy.

Practice 12.7

Fix the bug

For value = True this program should print Boolean. It prints whole number. Fix it so that it also still works for a value such as 7.

The program prints the lines below. Your program must print exactly these lines.

Example run

Boolean

12.8 A glimpse of what else patterns can do

Two more kinds of pattern belong with data types you have not met yet. A preview, so you recognise them later:

Dictionaries. A dictionary stores named pieces of data → Chapter 31. A pattern in curly brackets checks that certain names are present and captures their values:

shape = {"kind": "circle", "radius": 5}
match shape:
    case {"kind": "circle", "radius": r}:
        print("Circle, area about", round(3.14159 * r * r, 1))
    case {"kind": "rectangle", "width": w, "height": h}:
        print("Rectangle, area", w * h)

Output

Circle, area about 78.5

This is extremely useful for data that arrives from web services, which is usually built from dictionaries and lists → Chapter 66.

Your own classes. When you define your own types → Chapter 44, patterns such as case Point(x=0, y=0): can match on them and take them apart → Chapter 49.

12.9 match or if?

match does not replace if. They are good at different things.

Situation Best tool Why
A true-or-false question if there is nothing to match
Number ranges: under 40, 40 to 59, ... if / elif patterns cannot express <; you would need a guard on every case
Conditions about different variables if / elif match looks at one subject
One value against a list of fixed options either; match is tidier no repeated x ==
The shape of data: how many parts, which words, which types match this is what it is for
Taking pieces out while checking match capture does both in one step

A good test: if every case would need a guard, use if. If your if conditions are full of len(...) ==, index numbers and type checks, use match.

Practice 12.9

Multiple choice

You plan a match, and you notice that every case would need a guard. What does the chapter suggest?

Choose one answer

12.10 Common mistakes

The mistake What you see The fix
A bare name to compare with a variable: case LIMIT: It always matches, and overwrites LIMIT A literal, a guard (case n if n == LIMIT:) or a dotted name
case _: or a capture that is not last SyntaxError: ... makes remaining patterns unreachable Put the catch-all last
or in place of the bar: case "y" or "yes": SyntaxError case "y" | "yes":
Matching input text against numbers: case 1: Never matches, because the subject is "1" case "1":, or convert the subject first
Forgetting the brackets on a type: case str: Captures everything and overwrites str case str():
case int(): before case bool(): True is reported as an integer Put bool() first
Expecting cases to "fall through" Only one block ever runs Combine values with |
No wildcard, and nothing matches Silence End with case _:
Expecting a list pattern to match a string's characters No match Patterns in [ ] never match a str
Wrong indentation of case IndentationError case lines are indented under match; blocks under case

12.11 Putting it together

Practice 12.11

Write code

Shop commands. Read one line. If it is buy and one more word, print You buy the lamp. with that word in place of lamp. If it is sell and one more word, print You sell the lamp. in the same way. If it is the single word list, print The bag is empty.. For every other line, print Unknown command.

With the reply buy lamp, the program prints the lines below. Your program must print exactly these lines.

Example run

You buy the lamp.

12.12 How match works inside Python

Practice 12.12

Multiple choice

A program begins with match input("> ").split(): and has five cases. How many times is the user asked for a line?

Choose one answer

+ Practice

Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.

Questions

Check yourself

In match x:, what is x called? How many times is it worked out?

Show the answer

The subject. It is worked out exactly once, before any pattern is tried.

Check yourself

How many case blocks can run in one match? What happens if none of the patterns fits?

Show the answer

At most one. If no pattern fits, no block runs and the program carries on after the match, with no error.

Check yourself

What does case _: mean, and where must it go?

Show the answer

It is the wildcard: it fits any value. It must be the last case, because nothing after it could ever be reached.

Check yourself

What is the difference between case "quit": and case quit:?

Show the answer

case "quit": is a literal pattern and fits only the string "quit". case quit: is a capture pattern: it fits anything and stores the subject in a variable named quit.

Check yourself

Why does case "y" or "yes": not work? What should you write?

Show the answer

or is not allowed inside a pattern. Alternatives are separated with a bar: case "y" | "yes":.

Check yourself

What is a guard? Write a case that matches any number greater than 100 and calls it big.

Show the answer

A guard is an if condition added to a case, checked after the pattern fits. case big if big > 100:.

Check yourself

Which three things does the pattern ["take", item] check, and what does it assign?

Show the answer

That the subject is a sequence (and not a string), that it has exactly two items, and that the first item equals "take". It assigns the second item to item.

Check yourself

What does *rest capture in case [first, *rest]: when the subject is ["a"]?

Show the answer

An empty list, []. first is "a" and nothing is left over.

Check yourself

Why should case bool(): come before case int():?

Show the answer

bool is a kind of int, so int() also fits True and False. Testing bool() first lets the more specific case win.

Check yourself

Give one situation where if/elif is the better choice and one where match is.

Show the answer

if/elif: number ranges, or conditions about several different variables. match: one value against fixed options, or checking the shape of data such as a command with several words.

Predict the output

Predict the output

code = "B"
match code:
    case "A":
        print("first")
    case "B" | "C":
        print("second")
    case "B":
        print("third")
    case _:
        print("other")

Predict the output

n = 7
match n:
    case 0:
        print("zero")
    case x if x % 2 == 0:
        print("even")
    case x:
        print("odd", x + 1)

Predict the output

words = "open red door now".split()
match words:
    case ["open", thing]:
        print("A", thing)
    case ["open", colour, thing]:
        print("B", colour, thing)
    case ["open", *details]:
        print("C", len(details), details[-1])
    case _:
        print("D")

Predict the output

pair = (3, 0)
match pair:
    case (0, 0):
        print("both zero")
    case (x, 0):
        print("second is zero, first is", x)
    case (0, y):
        print("first is zero")
    case (x, y):
        print("neither")

Predict the output

item = "42"
match item:
    case int():
        print("int")
    case str(s) if s.isdigit():
        print("digits", int(s) + 1)
    case str():
        print("text")

Fix the bug

Fix the bug

For level = "low", this prints Maximum power.

After your fix, the program must print Normal power when the level is not high.

The program prints the lines below. Your program must print exactly these lines.

Example run

Normal power

Fix the bug

This does not run.

The program prints the lines below. Your program must print exactly these lines.

Example run

Confirmed

Fix the bug

The user types 2, and the program prints Invalid choice.

With the reply 2, the program prints the lines below. Your program must print exactly these lines.

Example run

Coffee

Fix the bug

This does not run.

The program prints the lines below. Your program must print exactly these lines.

Example run

Get ready

Fix the bug

For value = "hello", this should print text. It prints number, and after it runs, int("5") no longer works.

The program prints the lines below. Your program must print exactly these lines.

Example run

text

Coding problems

Write code · Easy

Traffic light. Ask for a colour and print Stop for red, Get ready for amber or yellow, Go for green, and a message for anything else. Accept any mix of capitals.

Print exactly Stop, Get ready or Go. For any other reply, print That is not a traffic light colour.

With the reply red, the program prints the lines below. Your program must print exactly these lines.

Example run

Stop

Write code · Easy

Month lengths. Ask for a month number and print how many days it has in a year that is not a leap year, using | to group months. Give a message for a number that is not 1 to 12.

Print only the number of days. For a number that is not 1 to 12, print A month number is from 1 to 12.

With the reply 9, the program prints the lines below. Your program must print exactly these lines.

Example run

30

Write code · Easy

Vowel check. Ask for one letter and use match to print whether it is a vowel, a consonant, or not a single letter at all.

Accept capital letters too. Print exactly vowel, consonant or Please type exactly one letter.

With the reply K, the program prints the lines below. Your program must print exactly these lines.

Example run

consonant

Write code · Medium

Rock, paper, scissors. Ask two players for their choices and print who wins, by matching on the pair (first, second). Handle a draw and invalid choices.

Ask player 1 first, then player 2. Print exactly Player 1 wins, Player 2 wins or Draw. If a choice is not valid, print Choose rock, paper or scissors.

With the replies rock then scissors, the program prints the lines below. Your program must print exactly these lines.

Example run

Player 1 wins

Write code · Medium

Describe a point. Given a pair (x, y), print whether it is the origin, on an axis (and which one, with the distance from the origin), or elsewhere. Use capture patterns to get the non-zero value.

For the check, ask for two whole numbers: x first, then y. Print one line in one of these forms: origin, on the x-axis, 5 from the origin, on the y-axis, 6 from the origin, elsewhere, at 3 across and -2 up.

With the replies 0 then 0, the program prints the lines below. Your program must print exactly these lines.

Example run

origin

Write code · Medium

Unit converter. Read a line such as 10 km or 3.5 miles, and convert kilometres to miles or miles to kilometres (1 mile is 1.609 km). Accept km or kilometres, and mi or miles. Reject anything that does not have exactly two parts.

Round the result to 2 decimal places and print it with its new unit, in the form 6.22 miles or 16.09 km. For a unit you do not know, print I do not know the unit 'metres'. with the typed unit. For a line that does not have exactly two parts, print Type a number and a unit, for example: 10 km

With the reply 10 km, the program prints the lines below. Your program must print exactly these lines.

Example run

6.22 miles

Write code · Hard

Grading with a twist. Ask for marks out of 100 and print a grade (90+ is A, 75+ is B, 60+ is C, 40+ is D, otherwise F), using match with guards. Also reject marks outside 0 to 100. Then write a sentence comparing this with the if/elif version from Chapter 11: which is clearer, and why?

Print only the grade letter. For marks outside 0 to 100, print Marks must be from 0 to 100. The sentence that compares the two versions is for you; it is not checked.

With the reply 82, the program prints the lines below. Your program must print exactly these lines.

Example run

B

Write code · Hard

Tiny robot. A robot understands forward N, back N, turn left, turn right and stop, where N must be made only of digits. For one typed command, print a description of what the robot does, or a helpful error. Reject forward with no number, and forward ten.

For a correct command, print one of these lines: The robot moves forward 5 steps., The robot moves back 5 steps., The robot turns left., The robot turns right., The robot stops. The wording of your error messages is your choice. Only correct commands are checked, so test the wrong ones yourself.

With the reply forward 5, the program prints the lines below. Your program must print exactly these lines.

Example run

The robot moves forward 5 steps.

Write code · Hard

What is it?. Write a match that describes any value: a Boolean, a whole number (positive, negative or zero), a decimal, an empty string, a one-character string, a longer string, None, an empty list, or a list (saying how many items and what the first one is). Test it with at least eight different values.

This one is not checked automatically. Run your program, then compare it with the book's answer.

Show the book's answer

bool() is tested before int(), and the more specific string and list shapes before the general ones.

value = ["x", "y", "z"]
match value:
    case bool():
        print("a Boolean")
    case int(n) if n > 0:
        print("a positive whole number")
    case int(n) if n < 0:
        print("a negative whole number")
    case int():
        print("zero")
    case float():
        print("a decimal number")
    case "":
        print("an empty string")
    case str(s) if len(s) == 1:
        print("a single character")
    case str():
        print("a longer string")
    case None:
        print("None")
    case []:
        print("an empty list")
    case [first, *rest]:
        print(f"a list of {len(rest) + 1} items, starting with {first!r}")
    case _:
        print("something else")

Output

a list of 3 items, starting with 'x'

Change the first line to try other values, such as True, -3, 0, 2.5, "", "q", "hello", None and []. The !r inside the f-string asks for the repr form, so the string is shown with its quotes → Chapter 16.

More practice

Write code

The locked door. Ask two questions, in this order: does the visitor have the key, and does the visitor know the code. Each reply is yes or no. Match on the pair of replies and print exactly one line: The door opens for two yes replies, You need the code for yes then no, You need the key for no then yes, and The door stays locked for anything else.

With the replies yes then yes, the program prints the lines below. Your program must print exactly these lines.

Example run

The door opens

Chapter project: Post office desk

Project

Price one order at a post office. The clerk types one line and the program prints one line. Capital letters, and spaces at the ends of the line, must make no difference.

The line What to print
letter or postcard Cost in dollars: 1
parcel and a weight in whole kg, up to 30 Cost in dollars: 10 (the cost is 4 dollars plus 2 dollars for each kg)
parcel and a weight above 30 Too heavy. The limit is 30 kg.
parcel and a second word that is not made only of digits The weight must be a whole number.
parcel alone, or with more than one extra word Type parcel and one weight, for example: parcel 3
an empty line Type an order.
anything else Unknown order 'box'. with the first word of the line in the quotes

Use one match on the words of the line. Think about the order of the cases: specific before general.

With the reply parcel 3, the program prints the lines below. Your program must print exactly these lines.

Example run

Cost in dollars: 10