← Practice
πŸ“– Flexible function argumentsLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 2/5Β·~15 min

*args/**kwargs: tally the lot

Sometimes a function should accept whatever you throw at it. Python has two catch-alls for that:

  • *args scoops up extra positional arguments into a tuple.
  • **kwargs scoops up extra keyword arguments into a dict.
python
def show(*args, **kwargs):
    return [args, kwargs]

show(1, 2, name="x")   # [(1, 2), {'name': 'x'}]

Inside the function, args is a tuple of the loose positionals and kwargs is a dict of the loose keywords. You iterate them like any tuple/dict.

Your task

Write tally(*nums, **bonuses) that returns the sum of every positional number plus the sum of every keyword value. Think of it as a register: the positionals are line items, the keywords are named bonuses, and you want the grand total.

python
tally(1, 2, 3)          # 6
tally(1, 2, a=10, b=5)  # 18
tally()                 # 0   (nothing in, nothing out)
tally(5, x=5)           # 10

Hint: inside the function nums is a tuple and bonuses is a dict β€” total the tuple, total the dict's values, and add the two results.

Tests

  • three positionals
  • positionals and keywords
  • nothing at all
  • one of each

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.