← Practice
πŸ“– Flexible function argumentsargs-kwargs-tally
LessonΒ·difficulty 2/5Β·~15 min

*args/**kwargs: tally the lot

*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: sum(nums) handles the positionals; sum(bonuses.values()) handles the keyword values. Add them together.

Tests

  • three positionals
  • positionals and keywords
  • nothing at all
  • one of each
  • only keywords (hidden)
  • only positionals (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.