For some functions, you may want to make some parameters as optional and use default values if the user does not want to provide values for such parameters. This is done with the help of default argument values. You can specify default argument values for parameters by following the parameter name in the function definition with the assignment operator (=) followed by the default argument.
Note that the default argument value should be immutable. This may not make much sense now but you will understand it when you come to the later chapters. Just remember that you have to use only immutable values and you cannot use mutable objects such as lists for default argument values.
Example 7.5. Using Default Argument Values
#!/usr/bin/python # Filename : func_default.py def say(s, times = 1): print s * times say('Hello') say('World', 5)
The function named say is used to print a string as number of times as we want. If we don't supply a value, then by default, the string is printed just once. This is done by giving a default argument value of 1 to the parameter times. 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 argument 5 stating that we want to say the string 5 times.
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 values are assigned to the parameters by position. For example, def func(a, b=5) is valid, but def func(a=5, b) is not valid.