What day is it?
Monday: swimming. Wednesday: art class. Saturday: the park. Any other day: play at home.
04CONDITIONALS · MATCH
Many languages have a switch to pick one option from a list. Python calls it match, and each option is a case.
IN REAL LIFE
Look at one thing, like the day or the button, and pick the option that fits.
Monday: swimming. Wednesday: art class. Saturday: the park. Any other day: play at home.
1: hide and seek. 2: jump rope. 3: draw a monster. Any other number: you choose!
Press A: orange juice. Press B: mango juice. Any other button: water.
LOOK FIRST
match command: means: let us look at what is inside command.
case "jump": runs its path when the box holds "jump".
The _ means “anything else”. It works like else.
switch → match Heads up: Python has no switch word. Since Python 3.10, it uses match and case.
STEP BY STEP
PyBot compares the box with each case, from the top.
day = "saturday"A box keeps the word saturday.match day:Look inside the day box. case "friday":Is it friday? No. Try the next case. print("school")Skipped. case "saturday":Is it saturday? Yes! print("play")This path runs. case _:Skipped. A case already fit. print("rest")case _ runs only when no other case fits.LOOK FIRST
Python picks the first case that fits, then leaves the match.
_ fits anything, so the cases below it would never get a turn.
case "saturday" | "sunday": fits both days with one path.
RUN IT
Guess first. Then run real Python and check.
command = "jump"
match command:
case "walk":
print("PyBot walks")
case "jump":
print("PyBot jumps")
case _:
print("PyBot waits")What will Python show?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change "jump" to "walk", then to "dance". Which case fits each time?
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
What does PyBot do today?
Other languages say switch. Which word does Python use?
fruit = "apple"
match fruit:
case "banana":
print("yellow")
case "apple":
print("red")
case _:
print("unknown")What does Python show?
animal = "cow"
match animal:
case "dog":
print("woof")
case "cat":
print("meow")
case _:
print("hmm")What does Python show?
What does case _ mean?
day = "sunday"
match day:
case "saturday" | "sunday":
print("weekend")
case _:
print("school day")What does Python show?
color = "red"
match color:
case "red":
print("stop")
case _:
print("other")_ fits anything, even red. What shows?
match can do the same job as…
PyBot used the word from other languages. Change it to Python's word.
meowOUTPUT
Want a fresh start? Clear only this page.
Other languages call it switch. In Python it is match, with case _ for anything else.