Python · Level 2 Functions

Flexible Arguments

Write functions that accept any number of positional and keyword arguments — the trick behind print() and many library APIs.

  • *args collects extra positional arguments into a tuple
  • **kwargs collects keyword arguments into a dict
  • Keyword arguments keep the order they were passed in

A parameter starting with * collects any extra positional arguments into a tuple; one starting with ** collects keyword arguments into a dict.

def report(title, *values, **options):
    print(title, values, options)

report("Scores", 90, 75, unit="pts")
# Scores (90, 75) {'unit': 'pts'}

Write make_tag(tag, *children, **attrs) that returns an HTML string: the children joined together inside the tag, and each keyword argument as an attribute, e.g. make_tag("a", "Docs", href="/docs") returns <a href="/docs">Docs</a>.

solution.py
Test Suites Pending
Stdout