Practice: Match-Case Statement
Q1. Weekday name
Set n = 2. Use match to print 'Mon' for 1, 'Tue' for 2, 'Wed' for 3, otherwise 'Other'.
Goal: Write a basic match.
Q2. Vowel or not
Set ch = 'e'. Use match with | to print 'vowel' for a, e, i, o, u, else 'consonant'.
Goal: Use alternatives.
Q3. Calculator
Set op = '*', a = 6, b = 7. Match op for '+', '-', '*' and print the result; otherwise print 'bad op'.
Goal: Match operators.
Q4. Weekend check
Set day = 'Sat'. Print 'weekend' for 'Sat' or 'Sun', otherwise 'weekday'.
Goal: Group cases.
Q5. Grade with guards
Set marks = 68. Print 'A' for 90+, 'B' for 75+, 'C' for 60+, else 'F' using match with guards.
Goal: Use guards.
Q6. Command words
Set cmd = ['go', 'east']. Match ['go', d] to print 'Going east'; match ['stop'] to print 'Stopping'; else 'Unknown'.
Goal: Match sequences.
Q7. Point location
Set point = (0, 5). Print 'origin' for (0,0), 'on y axis' for (0, y) with y not 0, 'on x axis' for (x, 0), else 'elsewhere'.
Goal: Match tuples.
Q8. Wildcard output
What does this print?
x = 7
match x:
case 1:
print('one')
case 2:
print('two')
case _:
print('many')Goal: Trace match.
Q9. First case wins
What does this print?
x = 2
match x:
case 2:
print('first')
case 2 | 3:
print('second')
case _:
print('third')Goal: Understand no fall-through.
Q10. Or pattern
What does this print?
c = 'b'
match c:
case 'a' | 'b':
print('early')
case _:
print('late')Goal: Use | patterns.
Q11. Guard output
What does this print?
n = 5
match n:
case x if x > 10:
print('big')
case x if x > 3:
print('medium', x)
case _:
print('small')Goal: Read guards.
Q12. Capture
What does this print?
pair = (3, 4)
match pair:
case (a, b):
print(a + b)Goal: Understand captures.
Q13. Star capture
What does this print?
items = [1, 2, 3, 4]
match items:
case [first, *rest]:
print(first)
print(rest)Goal: Use star patterns.
Q14. Case sensitivity
What does this print?
s = 'Yes'
match s:
case 'yes':
print('lower')
case 'Yes':
print('title')
case _:
print('none')Goal: Remember exact matching.
Q15. Fix the capture trap
The code should print 'ten' for n = 10, but the bare name always matches. Fix it using a guard.
limit = 10
n = 10
match n:
case limit:
print('ten')
case _:
print('other')Goal: Avoid capture mistakes.
Q16. Fix the wildcard position
This code raises a SyntaxError. Make it print 'two'.
n = 2
match n:
case _:
print('any')
case 2:
print('two')Goal: Order cases properly.
Q17. Fix the break
Remove the unneeded break so the code is correct Python and prints 'b'.
k = 2
match k:
case 1:
print('a')
break
case 2:
print('b')
breakGoal: Know match has no fall-through.
Q18. Fix the range
Fix the invalid range case so it prints 'low' for n = 3.
n = 3
match n:
case 1..5:
print('low')
case _:
print('high')Goal: Use guards for ranges.
Q19. Match versus elif
Name one situation where if-elif is a better fit than match.
Goal: Choose the right tool.
Q20. Meaning of underscore
What does case _ do in a match statement?
Goal: Understand the wildcard.