def perimeter(*args):
sides = len(args)
print('There are', sides, 'sides to the object')
total = 0
for i in range(0, sides):
total = total + args[i]
return total
object1 = perimeter(2, 3, 4)
print('The perimeter of object1 is:', object1)
object2 = perimeter(10, 20, 10, 20)
print('The perimeter of object2 is:', object2)
object3 = perimeter(10, 10, 10, 10, 10, 10, 10, 10)
print('The perimeter of object3 is:', object3)
In the script1205.py code, the perimeter() function uses the *args parameter variable to
define the parameters for the function. Because you don’t know how many arguments are used when
the function is called, the code uses the len() function to find out how many values are in the args
tuple.
While you could just use the for() loop to directly iterate through the args tuple, this example
demonstrates retrieving each value individually. The script1205.py code uses a for() loop to
iterate through a range from 0 to the number of values that the tuple contains and then uses the
arg[i] variable to reference each value directly. When the for loop is complete, the
perimeter() function returns the final value.
This example shows three different examples of using the perimeter() function, each with a
different number of arguments. In each case, the perimeter() function totals the argument values
and returns the result. When you run the script1205.py script, you should see the following
output:
Click here to view code image
pi@raspberrypi ~$ python3 script1205.py
There are 3 sides to the object
The perimeter of object1 is: 9
There are 4 sides to the object
The perimeter of object2 is: 60
There are 8 sides to the object
The perimeter of object3 is: 80
pi@raspberrypi ~$
By the Way: The args Variable
The examples in this section use the variable args to represent the tuple of the
argument values. This is not a requirement; you can use any variable name you choose.
However, it’s become somewhat of a de facto standard in Python to use the args
variable name in this situation.
Retrieving Values Using Dictionaries
You can use a dictionary variable to retrieve the argument values passed to a function. To do this, you
place two asterisks (**) before the dictionary variable name in the function definition parameter: