Function Parameters · Practice

Quiz & exercises

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

Quiz

1. In def area(width, height): ... followed by the call area(w, 5), which statement is correct?
2. What does this print?
def f(a, b=2, c=3):
    print(a, b, c)

f(10, c=30)
3. Which of these function definitions is a syntax error?
4. What does this print?
a, b = 1, 2
a, b = b, a + b
print(a, b)
5. What does this print?
a, *b, c = 'hello'
print(b)
6. What does this print?
d1 = {'a': 1, 'b': 2}
d2 = {'b': 20, 'c': 30}
print({**d2, **d1})
7. What does this print?
def f(a, b=2, *args):
    print(a, b, args)

f(1, 'x', 'y')
8. What happens with this code?
def f(*args, sep):
    print(args, sep)

f(1, 2, 3)
9. What does this print?
def f(a, **kwargs):
    print(a, kwargs)

f(b=2, a=1, c=3)
10. Given def f(x, /, y, *, z): ..., which call is valid?
11. What does this print?
def append_to(item, target=[]):
    target.append(item)
    return target

append_to(1)
print(append_to(2))
12. Why is if items is None: items = [] preferred over if not items: items = [] for a parameter defaulting to None?
13. What does this print?
[first, *rest] = ('a', 'b', 'c')
print(first, rest)
14. What happens here?
def f(a, b=10, *args):
    return a, b, args

f(1, 2, 3, b=5)
15. What does this print?
def f(*args):
    args[0].append(99)

x = [1, 2]
f(x)
print(x)

Coding exercises

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

Exercise 1: An average with options

Write a function average that accepts one or more numbers as positional arguments and returns their mean.

It should also accept a keyword-only option round_to (default None). When round_to is given, return the mean rounded to that many decimals with round().

Calling average() with no numbers must raise a TypeError (let Python do that for you through the signature), and average(1, 2, 2) must not treat the last 2 as round_to.

Hints (3)
  1. A required first parameter followed by *rest means "one or more values".
  2. Any parameter placed after *rest can only be passed by name, which is exactly what round_to needs.
  3. Test round_to is not None, so that round_to=0 still works.
Show a solution
def average(first, *rest, round_to=None):
    total = first + sum(rest)
    result = total / (1 + len(rest))
    if round_to is not None:
        result = round(result, round_to)
    return result

Exercise 2: Merge settings with overrides

Write merge_settings(*configs, **overrides) that combines any number of dictionaries into a new dictionary.

Later dictionaries win over earlier ones, and keyword arguments win over everything. The input dictionaries must not be modified.

Example: merge_settings({'a': 1, 'b': 2}, {'b': 3}, c=4) returns {'a': 1, 'b': 3, 'c': 4}.

Hints (3)
  1. configs is a tuple of dictionaries and overrides is a dictionary.
  2. {**a, **b} builds a new dict in which keys from b win.
  3. Start from an empty dict so that you never modify the caller's dictionaries, and so that zero arguments works.
Show a solution
def merge_settings(*configs, **overrides):
    result = {}
    for cfg in configs:
        result = {**result, **cfg}
    return {**result, **overrides}

Exercise 3: Forward any call

Write call_n(fn, *args, times=1, **kwargs) that calls fn with the given positional and keyword arguments times times, and returns a list of the results.

times must be keyword-only, so every positional argument after fn belongs to fn.

Example: call_n(pow, 2, 3, times=2) returns [8, 8], and call_n(sorted, [3, 1, 2], reverse=True) returns [[3, 2, 1]].

Hints (2)
  1. Move times after *args to make it keyword-only.
  2. Inside the function, args is a tuple and kwargs a dict. Unpack them again with fn(*args, **kwargs).
Show a solution
def call_n(fn, *args, times=1, **kwargs):
    return [fn(*args, **kwargs) for _ in range(times)]

Exercise 4: Fix the shared default

add_tag(tag, tags=[]) should add tag to the list tags and return it. When no list is passed, each call must start with a new empty list. But the current version shares one list between all such calls.

Fix it. When the caller does pass a list, even an empty one, the tag must be appended to that list (the caller's object).

Hints (2)
  1. The default [] is created once, when def runs. Use None as the default instead.
  2. Check tags is None rather than not tags: an empty list is falsy too, and it belongs to the caller.
Show a solution
def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags