Practice: *args and **kwargs
Q1. Average of many numbers
Write `average(*nums)` that returns the mean of the numbers. Print `average(2, 4, 6, 8)`.
Goal: Collect values with *args.
Q2. Print options sorted
Write `show(**kwargs)` that prints each `key=value` pair in alphabetical key order. Call `show(b=2, a=1, c=3)`.
Goal: Read **kwargs.
Q3. Longest word
Write `longest(*words)` that returns the longest word given (first one wins ties). Print `longest('pear', 'banana', 'kiwi')`.
Goal: Loop over *args.
Q4. Spread a list into a call
Given `def volume(l, w, h)` and `dims = [2, 3, 4]`, call `volume` with the list unpacked and print the result.
Goal: Unpack a list with *.
Q5. Build a tag
Write `tag(name, *content, **attrs)` that returns an HTML-like string. `tag('a', 'Home', href='/')` should give `<a href="/">Home</a>`. Print it.
Goal: Combine all parameter kinds.
Q6. Count of args
What does this print?
def f(*args):
return len(args)
print(f(1, 2, 3), f())Goal: Know args is a tuple.
Q7. Type of kwargs
What does this print?
def f(**kw):
return type(kw).__name__
print(f(a=1))Goal: Know kwargs is a dict.
Q8. Mixed call
What does this print?
def f(a, *b, **c):
print(a, b, c)
f(1, 2, 3, x=4)Goal: Trace parameter filling.
Q9. Star in the call
What does this print?
def f(a, b, c):
return a + b + c
vals = (1, 2, 3)
print(f(*vals), f(*vals[:2], 10))Goal: Unpack sequences in calls.
Q10. Keyword-only
What does this print?
def f(*items, sep='-'):
return sep.join(items)
print(f('a', 'b', 'c'))
print(f('a', 'b', sep='+'))Goal: Keyword-only parameters.
Q11. Dictionary unpack
What does this print?
def f(x, y=0, **extra):
return x, y, extra
d = {'x': 1, 'z': 9}
print(f(**d))Goal: Unpack dictionaries.
Q12. Fix the header order
This function raises a SyntaxError. Fix it.
def f(**kwargs, *args):
print(args, kwargs)
f(1, a=2)Goal: Order parameters correctly.
Q13. Missing star in call
The function should add the three numbers in the list but raises TypeError. Fix it.
def add(a, b, c):
return a + b + c
nums = [1, 2, 3]
print(add(nums))Goal: Spread sequences.
Q14. Changing args
This code raises TypeError. Fix it so it prints the values with the first one doubled.
def f(*args):
args[0] = args[0] * 2
print(args)
f(5, 6)Goal: Know args is immutable.
Q15. Why use **kwargs?
In two or three sentences, explain when `**kwargs` is better than normal parameters.
Goal: Decide when to use kwargs.
Q16. Two meanings of the star
Explain the difference between `*` in `def f(*a)` and in `f(*a)`.
Goal: Separate packing and unpacking.
Q17. Wrapper that counts
Write a function `counted(func, *args, **kwargs)` that returns a tuple of the call result and the number of positional arguments. Print `counted(max, 4, 9, 2)`.
Goal: Forward arguments.
Q18. Settings with defaults
Write `make_user(name, **extra)` that returns a dictionary with `name` and a `role` defaulting to `'guest'`, plus any extras. Print `make_user('Asha', age=20)`.
Goal: Use kwargs for settings.
Q19. Merge dictionaries
Given `x = {'p': 1}` and `y = {'q': 2}`, build a single dictionary using `**` and print it.
Goal: Use ** to combine.