In Chapter 11 you wrote a menu as an if/elif chain:
choice="2"ifchoice=="1":
print("Your balance is 250 dollars.")elifchoice=="2":
print("How much would you like to deposit?")elifchoice=="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"matchchoice:
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?
Section 12.1 gives the version and the year.
The year was 2021, so it is not one of the oldest versions, and not the newest one.
The answer is: Python 3.10
match arrived in Python 3.10, in 2021. Older code and older tutorials never use it.
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"matchcolour:
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:
The case lines sit under match, and each block sits under its case. The wildcard goes last, because nothing after it could be reached.
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:
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"matchday:
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.
An or-pattern joins alternatives with |. The case fits when any one of the alternatives fits.
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
Output
What type is floor after the first line? What type are the patterns?
A number is never equal to a piece of text. Make the subject and the patterns the same type.
floor=int(input("Floor: "))matchfloor:
case0:
print("Lobby")case1 | 2:
print("Offices")case_:
print("No such floor")
The reply was converted to an int, so text patterns such as "0" can never fit. Number patterns fix it.
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"matchcommand:
case"start":
print("Starting...")case"stop":
print("Stopping...")caseother:
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"matchcolour:
caseRED:
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:
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.
LIMIT in the pattern is a bare name. Does a bare name compare?
A capture always fits, and it gives the name a new value.
It prints
Limit reached
80
case LIMIT: does not compare with 10. It captures the subject, so the block runs and LIMIT is overwritten.
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=-4matchtemperature:
case0:
print("Exactly freezing")casetift<0:
print(f"{t} is below freezing")casetift<15:
print(f"{t} is cold")caset:
print(f"{t} is mild or warm")
Output
-4 is below freezing
Read case t if t < 0: in two steps:
The pattern t fits anything and captures the subject as t.
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=15matchn:
casekifk>20:
print("large")casekifk%5==0:
print("multiple of five")casekifk>10:
print("medium")case_:
print("small")
Check the guards from the top. The first guard that is true wins.
Two of the guards are true for 15. Only the higher one runs its block.
It prints
multiple of five
Cases are tried in order. The second guard is the first true one, so the third case is never checked.
Fill in the blank
Fill in the guard so that every price below 10 is Cheap.
The pattern p fits anything. The guard then decides if the case counts, so only prices below 10 reach 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
print(s,"is too fast")
casesifs>120:
print(s,"is fine")
matchspeed:
cases:
speed=int(input("Speed: "))
A capture with no guard fits everything, so it must be the last case.
The message about a high speed belongs under the case with the guard.
speed=int(input("Speed: "))matchspeed:
casesifs>120:
print(s,"is too fast")cases:
print(s,"is fine")
The guarded case comes first. The plain capture case s: is the catch-all, and Python insists that a catch-all is last.
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
Output
case SECRET: captures the guess. It never compares, and it overwrites SECRET.
Capture the guess under a new name, then compare that name with SECRET in a guard.
SECRET="plum"guess=input("Guess the fruit: ")matchguess:
casegifg==SECRET:
print("Correct!")print("The secret was",SECRET)
A bare name in a pattern is a box to put things in. To compare with a variable, capture first and compare in a guard.
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
Output
Convert the reply with int(). The value 0 can be a literal pattern.
For the ranges, capture the weight and add a guard: case w if w < 0:. Test the negative numbers before the small parcels.
weight=int(input("Weight in kg: "))matchweight:
case0:
print("Nothing to send")casewifw<0:
print("Not a real weight")casewifw<=5:
print("Small parcel")case_:
print("Large parcel")
A literal handles the exact value and guards handle the ranges. The order matters: the first case that fits wins.
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"matchcommand.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:
Is the subject a sequence?
Does it have exactly two items?
Is the first item equal to "go"? (a literal: compared)
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()iflen(words)==1andwords[0]=="look":
print("You see a small room.")eliflen(words)==2andwords[0]=="go":
direction=words[1]print(f"You walk {direction}.")eliflen(words)==2andwords[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"matchcommand.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"matchcommand.split():
case["go",("north" | "south" | "east" | "west")asdirection]:
print(f"You walk {direction}.")case["go",("up" | "down")asdirection]:
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=0y=7match(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:
Read the note near the end of section 12.6 about strings and sequence patterns.
A pattern in square brackets never fits a str.
The answer is: no match
A sequence pattern does not treat a string as a sequence of characters, so the first case does not fit and the wildcard runs.
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=4y=0match(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
Which pattern fits anything and does not keep the value?
The wildcard can be used inside a pair pattern too.
x=4y=0match(x,y):
case(0,0):
print("origin")case(_,0):
print("on the x-axis")case_:
print("elsewhere")
Inside a sequence pattern, _ means one item that you do not care about.
Predict the output
What does it print?
year=1900match(year%4==0,year%100==0):
case(True,False):
print("leap year")case(True,True):
print("check 400")case_:
print("common year")
Work out the two comparisons first. The subject is a pair of Booleans.
1900 divides by 4 and also by 100. Find the row with that pair.
It prints
check 400
Both comparisons are true for 1900, so the subject is (True, True) and the second case fits.
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.
Output
Python stops at the first pattern that fits. Which case fits go north first?
Put the specific case before the general one.
line=input("> ")matchline.split():
case["go","north" | "south"]:
print("You walk on.")case["go",_]:
print("You cannot go that way.")case_:
print("Unknown command.")
["go", _] fits every go command of two words. A general case placed first swallows the specific cases below it.
12.7 Matching by type
A pattern can ask "what kind of value is this?" Write the type's name followed by brackets:
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"matchvalue:
caseint(number):
print(f"The number {number}, doubled is {number*2}")casestr(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:
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]matchdata:
case["move",int(dx),int(dy)]ifdx==0anddy==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
Output
bool is a kind of int, so case int(): also fits True and False.
True is an int too. With bool() first, the more specific case wins, and other whole numbers still reach int().
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:
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.9match 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?
Section 12.9 gives a short test for this choice.
When the patterns themselves do no work, match gives you nothing extra.
The answer is: Use if
Guards on every case mean the patterns describe nothing. A plain if/elif chain says the same thing with less to read.
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.
Output
Match on line.split(). A pattern with two items fits only a line of exactly two words.
In ["buy", item], the text is compared and the name item captures the second word.
line=input("> ")matchline.split():
case["buy",item]:
print(f"You buy the {item}.")case["sell",item]:
print(f"You sell the {item}.")case["list"]:
print("The bag is empty.")case_:
print("Unknown command.")
The shape does the checking: buy alone and buy red lamp have the wrong number of words, so they reach the wildcard.
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?
The expression after match is the subject.
Python works the subject out before any pattern is tried, and never again.
The answer is: 1 time
The subject is worked out once. Every case is then tried against that one stored value.
+ 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.
words="open red door now".split()matchwords:
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")
Count the words that split() gives. A pattern without a star needs exactly that many items.
The starred name takes every word after open. details[-1] is the last of them.
It prints
C 3 now
There are four words, so the two-item and three-item patterns do not fit. details is ["red", "door", "now"].
words="open red door now".split()matchwords:
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")
Output
C 3 now
Predict the output
pair=(3,0)matchpair:
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")
A pair pattern is checked position by position. A literal compares, a name captures.
The first position is 3 and the second is 0. Which case is the first one that fits both positions?
It prints
second is zero, first is 3
pair=(3,0)matchpair:
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")
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
Output
Turn the reply into lowercase before the match, so the patterns only need lowercase words.
Two colours share one message. Join their patterns with |.
colour=input("Colour: ").strip().lower()matchcolour:
case"red":
print("Stop")case"amber" | "yellow":
print("Get ready")case"green":
print("Go")case_:
print("That is not a traffic light colour.")
colour=input("Colour: ").strip().lower()matchcolour:
case"red":
print("Stop")case"amber" | "yellow":
print("Get ready")case"green":
print("Go")case_:
print("That is not a traffic light colour.")
Output
Colour: Yellow
Get ready
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
Output
Convert the reply with int(). Then the patterns are numbers, not text.
You need three groups of months: one for 31 days, one for 30 days, and February. The wildcard takes every other number.
month=int(input("Month number: "))matchmonth:
case1 | 3 | 5 | 7 | 8 | 10 | 12:
print(31)case4 | 6 | 9 | 11:
print(30)case2:
print(28)case_:
print("A month number is from 1 to 12.")
The reply is converted to an int, so the patterns are numbers.
month=int(input("Month number: "))matchmonth:
case1 | 3 | 5 | 7 | 8 | 10 | 12:
print(31)case4 | 6 | 9 | 11:
print(30)case2:
print(28)case_:
print("A month number is from 1 to 12.")
Output
Month number: 9
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
Output
Make the reply lowercase first. One case with | can list the five vowels.
a guard with len and isalpha.
letter=input("A letter: ").strip().lower()matchletter:
case"a" | "e" | "i" | "o" | "u":
print("vowel")caseotheriflen(other)==1andother.isalpha():
print("consonant")case_:
print("Please type exactly one letter.")
letter=input("A letter: ").strip().lower()matchletter:
case"a" | "e" | "i" | "o" | "u":
print("vowel")caseotheriflen(other)==1andother.isalpha():
print("consonant")case_:
print("Please type exactly one letter.")
Output
A letter: K
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
Output
Put both choices in a pair: match (first, second):. Reject invalid choices before anything else.
A guard can catch the draw: capture both items and compare them. The three pairs that win for player 1 can share one case with |.
first=input("Player 1: ").strip().lower()second=input("Player 2: ").strip().lower()choices=("rock","paper","scissors")match(first,second):
case(x,y)ifxnotinchoicesorynotinchoices:
print("Choose rock, paper or scissors.")case(x,y)ifx==y:
print("Draw")case("rock","scissors") | ("paper","rock") | ("scissors","paper"):
print("Player 1 wins")case_:
print("Player 2 wins")
The draw is caught with a guard. The three winning pairs for the first player share one case.
first=input("Player 1: ").strip().lower()second=input("Player 2: ").strip().lower()choices=("rock","paper","scissors")match(first,second):
case(x,y)ifxnotinchoicesorynotinchoices:
print("Choose rock, paper or scissors.")case(x,y)ifx==y:
print("Draw")case("rock","scissors") | ("paper","rock") | ("scissors","paper"):
print("Player 1 wins")case_:
print("Player 2 wins")
Output
Player 1: rock
Player 2: scissors
Player 1 wins
Invalid input is rejected first, so the final wildcard can safely mean "player 2 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
Output
Match on the pair (x, y). A 0 in a pattern compares, and a name captures.
The distance from the origin is never negative. abs() removes the minus sign.
x=int(input("x: "))y=int(input("y: "))match(x,y):
case(0,0):
print("origin")case(x,0):
print(f"on the x-axis, {abs(x)} from the origin")case(0,y):
print(f"on the y-axis, {abs(y)} from the origin")case(x,y):
print(f"elsewhere, at {x} across and {y} up")
point=(0,-6)matchpoint:
case(0,0):
print("origin")case(x,0):
print(f"on the x-axis, {abs(x)} from the origin")case(0,y):
print(f"on the y-axis, {abs(y)} from the origin")case(x,y):
print(f"elsewhere, at {x} across and {y} up")
Output
on the y-axis, 6 from the 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
Output
Match on line.split(). A pattern with two items fits only a line of exactly two parts.
The second item can be an or-pattern such as "km" | "kilometres". The first item is still text, so convert it with float().
line=input("Distance: ").strip().lower()matchline.split():
case[amount,"km" | "kilometres"]:
print(round(float(amount)/1.609,2),"miles")case[amount,"mi" | "miles"]:
print(round(float(amount)*1.609,2),"km")case[_,unit]:
print(f"I do not know the unit '{unit}'.")case_:
print("Type a number and a unit, for example: 10 km")
line=input("Distance: ").strip().lower()matchline.split():
case[amount,"km" | "kilometres"]:
print(round(float(amount)/1.609,2),"miles")case[amount,"mi" | "miles"]:
print(round(float(amount)*1.609,2),"km")case[_,unit]:
print(f"I do not know the unit '{unit}'.")case_:
print("Type a number and a unit, for example: 10 km")
Output
Distance: 10 km
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
Output
Capture the marks with a name and put the condition in a guard: case m if m >= 90:.
Reject the marks outside 0 to 100 in the first case. After that, test the highest grade first.
marks=int(input("Marks: "))matchmarks:
casemifm<0orm>100:
print("Marks must be from 0 to 100.")casemifm>=90:
print("A")casemifm>=75:
print("B")casemifm>=60:
print("C")casemifm>=40:
print("D")case_:
print("F")
marks=int(input("Marks: "))matchmarks:
casemifm<0orm>100:
print("Marks must be from 0 to 100.")casemifm>=90:
print("A")casemifm>=75:
print("B")casemifm>=60:
print("C")casemifm>=40:
print("D")case_:
print("F")
Output
Marks: 82
B
Every case needs a guard, and the pattern itself (m) does no work. The if/elif version says the same thing with less to read, so it is the clearer choice here. match earns its place when the patterns themselves describe something.
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.
Output
Match on line.split(). Use a guard with isdigit() on the captured number.
Put the guarded case first. A second case with the same shape and no guard can then explain what is wrong with the number.
line=input("Command: ").strip().lower()matchline.split():
case["forward",n]ifn.isdigit():
print(f"The robot moves forward {n} steps.")case["back",n]ifn.isdigit():
print(f"The robot moves back {n} steps.")case["forward" | "back",n]:
print(f"'{n}' is not a whole number of steps.")case["forward" | "back"]:
print("How many steps? For example: forward 5")case["turn",("left" | "right")asside]:
print(f"The robot turns {side}.")case["stop"]:
print("The robot stops.")case_:
print("Commands: forward N, back N, turn left, turn right, stop")
line=input("Command: ").strip().lower()matchline.split():
case["forward",n]ifn.isdigit():
print(f"The robot moves forward {n} steps.")case["back",n]ifn.isdigit():
print(f"The robot moves back {n} steps.")case["forward" | "back",n]:
print(f"'{n}' is not a whole number of steps.")case["forward" | "back"]:
print("How many steps? For example: forward 5")case["turn",("left" | "right")asside]:
print(f"The robot turns {side}.")case["stop"]:
print("The robot stops.")case_:
print("Commands: forward N, back N, turn left, turn right, stop")
Output
Command: forward ten
'ten' is not a whole number of steps.
The guarded cases come first. If the guard fails, the same shape is caught by the next case, which explains the problem.
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.
Output
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"]matchvalue:
casebool():
print("a Boolean")caseint(n)ifn>0:
print("a positive whole number")caseint(n)ifn<0:
print("a negative whole number")caseint():
print("zero")casefloat():
print("a decimal number")case"":
print("an empty string")casestr(s)iflen(s)==1:
print("a single character")casestr():
print("a longer string")caseNone:
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
Output
Put the two replies in round brackets with a comma: match (key, code):.
Each case is a pair of literal patterns, such as ("yes", "no"). A wildcard takes the remaining combinations.
key=input("Do you have the key? ")code=input("Do you know the code? ")match(key,code):
case("yes","yes"):
print("The door opens")case("yes","no"):
print("You need the code")case("no","yes"):
print("You need the key")case_:
print("The door stays locked")
Matching on a pair turns the decision into a small table, one row for each combination.
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
Output
Clean the line first with strip() and lower(). Then match on line.split(), as the calculator in section 12.11 did.
Three cases share the shape ["parcel", kg]. Two of them have a guard, and they come first: one with isdigit(), one that compares int(kg) with 30.
After the correct shapes, ["parcel", *_] catches a parcel with the wrong number of words, [] catches the empty line, and [kind, *_] catches every other order.
line=input("Order: ").strip().lower()matchline.split():
case["letter" | "postcard"]:
print("Cost in dollars: 1")case["parcel",kg]ifnotkg.isdigit():
print("The weight must be a whole number.")case["parcel",kg]ifint(kg)>30:
print("Too heavy. The limit is 30 kg.")case["parcel",kg]:
print("Cost in dollars:",4+2*int(kg))case["parcel",*_]:
print("Type parcel and one weight, for example: parcel 3")case[]:
print("Type an order.")case[kind,*_]:
print(f"Unknown order '{kind}'.")
The shape of the line does the validation, guards handle the weight, and the cases run from the most specific to the most general.