Function Parameters · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
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 ✓ Passed
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.
def average(numbers, round_to=None):
total = sum(numbers)
return total / len(numbers)
def test_basic():
"""average(2, 4) == 3"""
assert average(2, 4) == 3, f"got {average(2, 4)!r}"
def test_many():
"""works with any number of values"""
assert average(1, 2, 3, 4, 5) == 3
def test_single():
"""a single value is its own average"""
assert average(7) == 7
def test_round_to():
"""round_to rounds the result"""
assert average(1, 2, 2, round_to=2) == 1.67, f"got {average(1, 2, 2, round_to=2)!r}"
def test_round_to_keyword_only():
"""a third positional value is data, not round_to"""
assert average(1, 2, 2) == 5 / 3
def test_no_args():
"""average() raises TypeError"""
try:
average()
except TypeError:
return
assert False, "average() should raise TypeError"
Hints (3)
- A required first parameter followed by
*restmeans "one or more values". - Any parameter placed after
*restcan only be passed by name, which is exactly whatround_toneeds. - Test
round_to is not None, so thatround_to=0still 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 resultExercise 2: Merge settings with overrides ✓ Passed
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}.
def merge_settings(*configs, **overrides):
result = configs[0]
for cfg in configs[1:]:
result.update(cfg)
return result
def test_example():
"""later dicts and keywords win"""
result = merge_settings({'a': 1, 'b': 2}, {'b': 3}, c=4)
assert result == {'a': 1, 'b': 3, 'c': 4}, f"got {result!r}"
def test_keyword_wins():
"""keyword arguments override every dict"""
assert merge_settings({'x': 1}, {'x': 2}, x=3) == {'x': 3}
def test_no_mutation():
"""input dictionaries are not modified"""
first = {'a': 1}
merge_settings(first, {'a': 2, 'b': 3})
assert first == {'a': 1}, f"first dict was changed to {first}"
def test_new_object():
"""always returns a new dict"""
only = {'a': 1}
result = merge_settings(only)
assert result == only and result is not only
def test_empty():
"""no arguments gives an empty dict"""
assert merge_settings() == {}
Hints (3)
configsis a tuple of dictionaries andoverridesis a dictionary.{**a, **b}builds a new dict in which keys frombwin.- 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 ✓ Passed
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]].
def call_n(fn, times=1, *args, **kwargs):
return [fn(args, kwargs) for _ in range(times)]
def test_positional():
"""positional arguments are forwarded"""
assert call_n(pow, 2, 3, times=2) == [8, 8], f"got {call_n(pow, 2, 3, times=2)!r}"
def test_keyword():
"""keyword arguments are forwarded"""
assert call_n(sorted, [3, 1, 2], reverse=True) == [[3, 2, 1]]
def test_default_times():
"""times defaults to 1"""
assert call_n(max, 4, 9, 2) == [9]
def test_times_is_keyword_only():
"""the second positional argument goes to fn, not to times"""
assert call_n(abs, -5) == [5]
def test_called_n_times():
"""fn really is called `times` times"""
calls = []
call_n(calls.append, 'x', times=3)
assert calls == ['x', 'x', 'x'], f"calls were {calls!r}"
Hints (2)
- Move
timesafter*argsto make it keyword-only. - Inside the function,
argsis a tuple andkwargsa dict. Unpack them again withfn(*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 ✓ Passed
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).
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
def test_fresh_list():
"""two calls without a list don't share state"""
first = add_tag('a')
second = add_tag('b')
assert first == ['a'] and second == ['b'], f"got {first!r} and {second!r}"
def test_uses_callers_list():
"""appends to a list the caller provides"""
mine = ['x']
result = add_tag('y', mine)
assert mine == ['x', 'y'] and result is mine
def test_empty_callers_list():
"""an empty list passed by the caller is used, not replaced"""
mine = []
add_tag('z', mine)
assert mine == ['z'], f"caller's list is {mine!r}"
def test_default_is_none():
"""the default value is None"""
assert add_tag.__defaults__ == (None,), f"defaults are {add_tag.__defaults__!r}"
Hints (2)
- The default
[]is created once, whendefruns. UseNoneas the default instead. - Check
tags is Nonerather thannot 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