Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
Be careful when passing arguments to your Python functions. Python matches the
argument values in the same order that you define them in the function parameters.
These are called positional parameters.

Setting Default Parameter Values


Python allows you to set default values assigned to parameters if no arguments are provided when the
main program calls the function. You just set the default values inside the function definition, like this:


Click here to view code image


>>> def area(width = 10, height = 20):
area = width * height
return area
>>>

The area() function definition defines default values for the two parameters. If you call the
area() function with arguments, Python uses those arguments in the function and overrides the
default values, as shown here:


>>> total = area(15, 30)
>>> print(total)
450
>>>

However, if you call the function without any arguments, instead of giving you an error message,
Python uses the default values assigned to the parameters, like this:


>>> total2 = area()
>>> print(total2)
200
>>>

If you specify just one argument, Python uses it for the first parameter and takes the default for the
second parameter, as in this example:


>>> area(15)
300
>>>

If you want to define a value for the second parameter but not the first, you have to define the
argument value by name, like this:


>>> area(height=15)
150
>>>

You don’t have to declare default values for all the parameters. You can mix and match which ones
have default values, as shown here:


Click here to view code image


>>> def area2(width, height = 20):
area2 = width * height
print('The width is:', width)
print('The height is:', height)
print('The area is:', area2)
Free download pdf