def func5(**kwargs):
When you place the two asterisks in front of the kwargs variable, it becomes a dictionary variable.
When you call the func5() function, you must specify a keyword and value pair for each argument:
Click here to view code image
func5(one = 1, two = 2, three = 3)
To retrieve the values, you use the kwargs['one'], kwargs['two'], and
kwargs['three'] variables.
Listing 12.6 shows an example of using this method in the script1206.py Python script.
LISTING 12.6 Using Dictionaries in Functions
Click here to view code image
#!/usr/bin/python3
def volume(**kwargs):
radius = kwargs['radius']
height = kwargs['height']
print('The radius is:', radius)
print('The height is:', height)
total = 3.14159 * radius * radius * height
return total
object1 = volume(radius = 5, height = 30)
print('The volume of object1 is:', object1)
The script1206.py code demonstrates how the kwargs variable becomes a dictionary
variable, using the keywords you specify when you call the function. The kwargs['radius']
variable contains the value set to the radius value in the function call, and the kwargs['height']
variable contains the value set to the height value in the function call.
By the Way: The kwargs Variable
You can use any variable name for the dictionary variable, but the kwargs variable
name has become a de facto standard for defining dictionary parameters in Python
coding.
Handling Variables in a Function
As you can probably tell by now, handling variables in Python functions can be rather complex. To
make things even more complicated, there are two different types of variables that you can use inside
Python functions:
Local variables
Global variables
These two types of variables behave somewhat differently in your program code, so it’s important to
know just how they work. The following sections break down the differences between using local and