Unit 11: Patterns & Data
match, JSON and finding text.
Unit 11 of 31 in Python for kids. Its 5 lessons are Matching Cases, Saving Data as Text, Finding Patterns, Checking and Changing and Pattern Master — below is everything each one explains, and a question or two from it to try.
Every sample on this page was run through real Python before it shipped, and prints exactly what it says it prints.
This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.
🎛️ Matching Cases
A tidier if/elif chain
When you are checking one value against lots of possibilities, match reads better. Each case is one possibility.
Python
colour = "red"
match colour:
case "red":
print("Stop")
case "green":
print("Go")
It prints
Stop
The catch-all case
case _ means "anything else". It goes last, and it is how you stop your program silently doing nothing.
Python
animal = "fox"
match animal:
case "cat":
print("Meow")
case _:
print("I do not know that one")
It prints
I do not know that one
Several values in one case
A | between values means "any of these".
Python
day = "Sunday"
match day:
case "Saturday" | "Sunday":
print("Weekend!")
case _:
print("School day")
It prints
Weekend!
Try it yourself
What does this print?
Python
n = 3
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("lots")
What does case _: mean?
- An empty case
- Anything that none of the cases above matched
- A mistake
- Match nothing
Answer them in the app
💾 Saving Data as Text
What is JSON?
A dictionary lives in your program and vanishes when it stops. JSON is that same data written out as plain text, so it can be saved in a file or sent across the internet.
Python
import json
player = {"name": "Ada", "score": 10}
print(json.dumps(player))
It prints
{"name": "Ada", "score": 10}
And back again
dumps turns data into text. loads turns the text back into real Python data you can use.
Python
import json
text = '{"name": "Ada", "score": 10}'
player = json.loads(text)
print(player["name"])
print(player["score"] + 5)
It prints
Ada 15
Making it readable
indent spreads the text over several lines so a human can read it.
Python
import json
print(json.dumps({"a": 1, "b": 2}, indent=2))
It prints
{
"a": 1,
"b": 2
}
Try it yourself
Which way round is dumps?
- Text into data
- Data into text
- It deletes the data
- It prints the data
What does this print?
Python
import json
data = json.loads('{"pets": ["cat", "dog"]}')
print(len(data["pets"]))
Answer them in the app
🔍 Finding Patterns
Searching for a shape, not a word
in finds an exact word. A regular expression finds a *shape* — like "some digits" — wherever it appears. \d means one digit and + means one or more.
Python
import re
print(re.findall(r"\d+", "I have 3 cats and 12 fish"))
It prints
['3', '12']
Why the r?
The r before the quotes means "leave the backslashes alone". Without it Python tries to read \d itself and gets confused. Always put the r there.
Python
import re
print(re.findall(r"\w+", "hello there"))
It prints
['hello', 'there']
The full stop matches anything
A . in a pattern means "any single character". So c.t matches cat, cot and cut.
Python
import re
print(re.findall(r"c.t", "cat cot dog cut"))
It prints
['cat', 'cot', 'cut']
Try it yourself
What does \d mean in a pattern?
- The letter d
- Any one digit
- A dot
- A dollar
What does this print?
Python
import re
print(re.findall(r"\d+", "a1b22c333"))
Answer them in the app
✂️ Checking and Changing
Does the whole thing fit?
^ means "the start" and $ means "the end", so ^c.t$ matches only words that are exactly three letters starting c and ending t. fullmatch answers with something truthy, or None when it does not fit.
Python
import re
print(bool(re.fullmatch(r"^c.t$", "cat")))
print(bool(re.fullmatch(r"^c.t$", "chart")))
It prints
True False
Swapping things out
re.sub finds every match and replaces it. Great for hiding things.
Python
import re
print(re.sub(r"\d", "*", "my code is 1234"))
It prints
my code is ****
Try it yourself
What does this print?
Python
import re
print(re.sub(r"cat", "dog", "cat and cat"))
What does ^ mean at the start of a pattern?
- Not this
- Match must begin at the start of the text
- Go up a line
- A power, like 2^3
Answer them in the app
🏆 Pattern Master
Try it yourself
What does this print?
Python
grade = "B"
match grade:
case "A" | "B":
print("Great")
case _:
print("Keep going")
Answer it in the app