match and case
Python · Unit 21: Advanced Python
- Full plan
- Python
- 8 exercises
match compares a value against several shapes. Each case is one option, | accepts either of two, and case _ catches everything else.
It does the same job as a chain of if and elif, but it reads better when you always compare the same value.
def day_kind(d):
match d:
case "sat" | "sun":
return "rest"
case _:
return "work"
print(day_kind("sun"), day_kind("tue"))Prints
rest work
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Fill in the blank so any other color lets you go.
3. Predict the output
What does this code print?
4. Complete the code
Fill in the blank to keep the first item, however many there are.
5. Predict the output
What does this code print?
6. Find the bug
It should say off for Saturday and for Sunday. Which line has the error?
7. Find the case that fails
size(xs)should return "empty", "one" or "two" depending on how many items the list has, and "many" from three on. Which call fails?8. Put the lines in order
Put the lines in order to answer a message that arrives as a dictionary.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.