Editor settings

General settings

Save settings

Learn to program with Python

Accept a variable number of arguments with kwargs #

In the previous lesson, besides using args to receive an unlimited number of positional arguments, we can also receive an unlimited number of keyword arguments by using the ** symbol in the same way. The values that are specified when calling the function will be stored as a dictionary.

def do_something(**kwargs):
    print("keyword arguments: ", kwargs)

do_something(a="5", b="10", c="15")
Output:
keyword arguments:  {'a': '5', 'b': '10', 'c': '15'}

Furthermore, we can use args and kwargs together in the same function.

def do_something(*args, **kwargs):
    print("positional arguments:", args)
    print("keywr=ord arguments:", kwargs)

do_something(1, 2, 3, a="5", b="10", c="15")
Output:
positional arguments: (1, 2, 3)
keyword arguments: {'a': '5', 'b': '10', 'c': '15'}
We can use variable names other than args and kwargs, and the program will work the same way. However, using args and kwargs as variable names is common practice to represent positional and named arguments, respectively, that can accept an arbitrary number of values.

Exercise #

Create a function named accept_any_keyword_arguments that can take any number of keyword arguments.

Tests #

  • Create a function named accept_any_keyword_arguments
  • Function accept_any_keyword_arguments should accept any number of keyword arguments
Output will be displayed here