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:
*argsscoops up extra positional arguments into a tuple.**kwargsscoops 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.