Functions with variable-length keyword arguments (**kwargs)
Let's push further on what you've learned about flexible arguments - you've used *args
, you're now going to use **kwargs
! What makes **kwargs
different is that it allows you to pass a variable number of keyword arguments to functions. Recall from the previous video that, within the function definition, kwargs
is a dictionary.
To understand this idea better, you're going to use **kwargs
in this exercise to define a function that accepts a variable number of keyword arguments. The function simulates a simple status report system that prints out the status of a character in a movie.
This exercise is part of the course
Introduction to Functions in Python
Exercise instructions
- Complete the function header with the function name
report_status
. It accepts a single flexible argument**kwargs
. - Iterate over the key-value pairs of
kwargs
to print out the keys and values, separated by a colon ':'. - In the first call to
report_status()
, pass the following keyword-value pairs:name="luke"
,affiliation="jedi"
andstatus="missing"
. - In the second call to
report_status()
, pass the following keyword-value pairs:name="anakin"
,affiliation="sith lord"
andstatus="deceased"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define report_status
def ____(____):
"""Print out the status of a movie character."""
print("\nBEGIN: REPORT\n")
# Iterate over the key-value pairs of kwargs
for ____, ____ in kwargs.items():
# Print out the keys and values, separated by a colon ':'
print(____ + ": " + ____)
print("\nEND REPORT")
# First call to report_status()
# Second call to report_status()
report_status(name=____, affiliation=____, status=____)