Exercises
Match
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Match the command: start prints Starting, stop prints Stopping, anything else prints Unknown.
Python
command = "stop"
# match on command
case _ is the catch-all.
command = "stop"
match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
case _:
print("Unknown")Exercise 2Passed
Match the point and print origin, on the x axis, or elsewhere.
Python
point = (5, 0)
# match the pair
case (x, 0) matches any pair whose second item is zero, and binds x.
point = (5, 0)
match point:
case (0, 0):
print("origin")
case (x, 0):
print("on the x axis at", x)
case _:
print("elsewhere")Exercise 3Passed
Add a guard so negative numbers are reported separately.
Python
value = -3
match value:
case n if n > 10:
print(n, "large")
case n:
print(n, "small")A case can carry an if condition of its own. Put the negative case first.
value = -3
match value:
case n if n < 0:
print(n, "negative")
case n if n > 10:
print(n, "large")
case n:
print(n, "small")