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=}')
8. What does this print?
from collections import namedtuple
P = namedtuple('P', 'x y z', defaults=(0, 1))
print(P(5))
9. What does this print?
d = {'a': 1, 'b': 2, 'c': 3}
del d['a']
d['a'] = 10
d['b'] = 20
print(list(d))
10. Which statement about dictionary ordering is correct?
11. Which of these is not a valid numeric literal?
12. What does this print?
n = 255
print(f'{n:_b}', f'{1234567:_}')

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]

Exercise 3: A named tuple factory from kwargs

Write make_record(class_name, **fields) that returns a named tuple class whose field names are the keyword names in the order given, and whose default values are the keyword values.

For example, Point = make_record('Point', x=0, y=0, label='') should allow Point(5) to produce Point(x=5, y=0, label='').

Hints (2)
  1. Since Python 3.6, fields keeps the caller's order, so don't sort it.
  2. namedtuple accepts a defaults= argument (3.7+). Alternatively set Struct.__new__.__defaults__ = tuple(fields.values()).
Show a solution
from collections import namedtuple

def make_record(class_name, **fields):
    return namedtuple(class_name, fields.keys(), defaults=fields.values())