So far we have seen how both *args
and **kwargs
can be combined with standard arguments. This is useful, but in some cases, we may want to use all three types together! Thankfully Python allows us to do so as long as we follow the correct order in our function definition. The order is as follows:
- Standard positional arguments
*args
- Standard keyword arguments
**kwargs
As an example, this is what our function definition might look like if we wanted a function that printed animals utilizing all three types:
def print_animals(animal1, animal2, *args, animal4, **kwargs): print(animal1, animal2) print(args) print(animal4) print(kwargs)
We could call our function like so:
print_animals('Snake', 'Fish', 'Guinea Pig', 'Owl', animal4='Cat', animal5='Dog')
And our result would be:
Snake Fish ('Guinea Pig', 'Owl') Cat {'animal5': 'Dog'}
That is a whole lot of arguments! Let’s break it down:
The first two arguments that our function accepts will take the form of standard positional arguments. When we call the function, the first two values provided will map to
animal1
andanimal2
. Thus, the first line of output isSnake Fish
The non-keyword arguments that follow after
Snake
andFish
in our function call are all mapped to theargs
tuple. Thus, our result is('Guinea Pig', 'Owl')
Then we transition to regular keyword arguments. Since we called
animal4
as a keyword, our result for the print statement isCat
Lastly, we have one more keyword argument that is mapped to
**kwargs
. Thus, our last line of output is{'animal_5': 'Dog'}
Let’s practice putting it all together in our restaurant application for Jiho!
Instructions
For an upcoming holiday, Jiho plans on making a prix fixe menu for the restaurant. Customers at the restaurant will be able to choose the following:
- 1 Appetizer
- 2 Entrees
- 1 Side dish
- 2 Scoops of different ice cream flavors for dessert.
To accomplish all these choices, we are going to utilize the different types of arguments that we have learned so far. Now that we’ve set up our goals, hit “Run” to move on to the next step.
Let’s start by defining a function called single_prix_fixe_order()
which will define four parameters to accept the full order:
- A parameter named
appetizer
- A parameter named
entrees
paired with a*
operator - A parameter named
sides
- A parameter named
dessert_scoops
paired with a**
operator
Our function should simply have four print()
statements that print each individual parameter.
We got our first prix fixe order in! The customer wants the following:
'Baby Beets'
as an appetizer'Salmon'
and'Scallops'
as entrees'Mashed Potatoes'
as a side- A scoop of
'Vanilla'
ice cream and a scoop of'Cookies and Cream'
for dessert
Utilize our function single_prix_fixe_order()
to print out all of the customers order.