Python Updates · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
def classify(cmd):
    match cmd:
        case ["go", direction]:
            return f"go {direction}"
        case ["go", *rest]:
            return f"multi {len(rest)}"
        case _:
            return "unknown"

print(classify(["go", "north"]), classify(["go", "a", "b"]), classify("go north"))
2. What does this print?
l1 = [1, 2, 3]
l2 = 'ab'
try:
    print(list(zip(l1, l2, strict=True)))
except ValueError:
    print('mismatch')
3. What does this print?
d1 = {'a': 1, 'b': 2}
d2 = {'b': 20, 'c': 30}
print(d2 | d1)
4. What does this print?
s = 'mississippi'
print(s.lstrip('mis'), s.removeprefix('mis'))
5. What does this print?
values = [n for x in range(6) if (n := x * 2) > 6]
print(values, n)
6. Given def f(a, b, /, c, *, d): ..., which call is valid?
7. What does this print?
x = 3.5
label = 'pi'
print(f'{x=}, {label=}')

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: A command interpreter with match

Write run(command) that takes a list of words and uses a match statement to return:

- ["add", a, b] → the sum of the two numbers, e.g. run(["add", "2", "3"]) returns 5 (convert with int) - ["echo", *words] → the words joined with single spaces, e.g. run(["echo", "hi", "there"]) returns 'hi there' - ["quit"] or ["exit"] → the string 'bye' - anything else → raise ValueError

Hints (3)
  1. A pattern like ["add", a, b] only matches a sequence of exactly three items, binding the last two.
  2. Use *words to collect any number of remaining items, and | to combine ["quit"] and ["exit"] in one case.
  3. The wildcard _ catches everything else; raise the error there.
Show a solution
def run(command):
    match command:
        case ["add", a, b]:
            return int(a) + int(b)
        case ["echo", *words]:
            return " ".join(words)
        case ["quit"] | ["exit"]:
            return "bye"
        case _:
            raise ValueError(f"unknown command: {command!r}")

Exercise 2: Compute once, filter, keep

normalize(s) is an "expensive" function. Write long_words(words, min_len) that returns a list of the normalized versions of the words whose normalized length is at least min_len, in the original order.

Call normalize exactly once per word. A list comprehension with := is the neat way to do it.

Hints (2)
  1. The starter calls normalize twice for every word that passes the test.
  2. The if clause runs before the output expression, so do the assignment there: if len(n := normalize(w)) >= min_len.
Show a solution
calls = 0

def normalize(s):
    global calls
    calls += 1
    return s.strip().lower()

def long_words(words, min_len):
    return [n for w in words if len(n := normalize(w)) >= min_len]