Exercises
args and kwargs
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write total so it adds up any number of arguments.
Python
# define total
print(total(1, 2))
print(total(1, 2, 3, 4))
print(total())*numbers collects the positional arguments into a tuple.
def total(*numbers):
return sum(numbers)
print(total(1, 2))
print(total(1, 2, 3, 4))
print(total())Exercise 2Passed
Print each keyword argument as key = value.
Python
# define show
show(colour="red", size=10)**kwargs collects them into a dictionary.
def show(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
show(colour="red", size=10)Exercise 3Passed
Write a wrapper that passes everything straight through to the given function.
Python
def area(width, height=2):
return width * height
def call(fn, *args, **kwargs):
# call fn with whatever was passed
pass
print(call(area, 3, height=4))In a call, * and ** spread rather than collect.
def area(width, height=2):
return width * height
def call(fn, *args, **kwargs):
return fn(*args, **kwargs)
print(call(area, 3, height=4))