Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using Default Argument Values

Example 7.5. Using Default Argument Values

#!/usr/bin/python
# Filename: func_default.py def say(message, times = 1): print message * times say('Hello')
say('World', 5)

Output

$ python func_default.py Hello
WorldWorldWorldWorldWorld

How It Works

The function named say is used to print a string as many times as want. If we don't supply a value, then by default, the string is printed just once. We achieve this by specifying a default argument value of1 to the parametertimes.

In the first usage of say, we supply only the string and it prints the string once. In the second usage of say, we supply both the string and an argument5 stating that we want to say the string message 5 times.

Important

Only those parameters which are at the end of the parameter list can be given default argument values i.e. you cannot have a parameter with a default argument value before a parameter without a default argument value in the order of parameters declared in the function parameter list.

This is because the values are assigned to the parameters by position. For example, def func(a, b=5) is valid, butdef func(a=5, b) is not valid.