DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

What happens if you don’t know the total number of
arguments that are being passed to a function? When
you read in data, you might not know how many
arguments to expect. Python allows you to use * and
(often referred to as *args and *kwargs) to define any
number of arguments or keyword arguments.
and

allow you to iterate through a list or other collection of
data, as shown in this example:


Click here to view code image


>>> def hello(*args):
for arg in args:
print("Hello", arg, "!")

>>> hello('Caleb', 'Sydney', 'Savannah')
Hello Caleb!
Hello Sydney!
Hello Savannah!

By using keyword arguments, you can send a list of
key/value pairs to a function, as in the following
example:


Click here to view code image


>>> def hello(**kwargs):
for key, value in kwargs.items():
print("Hello", value, "!")

>>> hello(kwarg1='Caleb', kwarg2='Sydney',
kwarg3='Savannah')

Hello Caleb!
Hello Sydney!
Hello Savannah!

Note the use of the items() function in the for
statement to unpack and iterate through the values.

Free download pdf