Default parameter values
For some functions, you may want some of its parameters to be optional, and if the user does not want to provide values for these parameters, the parameters will use the default values. This function is done using the default parameter values. You can assign default parameter values to parameters by adding the assignment operator (=) and the default value after the parameter name of the function definition.
Note that the default parameter value should be a parameter. More precisely, the default parameter values should be immutable-this will be explained in detail in a later section. Keep this in mind from now on.
Using default parameter values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example 7.5 using default parameter values
#!/usr/bin/python#Filename:func_default.pydefSay (Message,times=1):PrintMessage *Times ;#if (a==1):#modifying default parameter values#times=2#Print message * times;#a=1Say'Hello') Say (' World', 5)
Output
$ python func_default.py
Hello
Worldworldworldworldworld
How it works
The function named say is used to print a string any number of times required. If we do not provide a value, then by default, the string will be printed only once. We do this by assigning a default parameter value to the parameter times.
When using say for the first time, we provide only one string, and the function prints the string only once. In the second use of say, we provided a string and a parameter of 5, indicating that we wanted to say this string message 5 times.
Important only those parameters at the end of the formal parameter list can have default argument values, which means that you cannot declare a parameter with a default value and then declare a formal parameter that has no default value when declaring a function parameter. This is because the value assigned to the parameter is assigned according to the position. For example, Def func (A, b=5) is valid, but def func (a=5, b) is not valid.
Default parameters of a function