Defining Default Parameters
When defining a function, you can also have default parameters.
For example, the python's own int () function, in fact, there are two parameters, we can both pass a parameter, and can pass two parameters:
>>> Int (' 123 ') 123>>> int (' 123 ', 8) 83
The second argument of the Int () function is the conversion, if not passed, the default is decimal (base=10), and if passed, use the passed in parameters.
As you can see, the function's default parameter is to simplify the call , and you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.
Let's define a function that calculates the n-th square of x:
#coding =gbkdef Power (x,n): If X==0:return ' please reenter: ' Else:return x**nprint (Power (1,3))
Assuming the maximum number of squares is calculated, we can set the default value of N to 2:
def power (x, n=2): s = 1 while n > 0: n = n-1 s = s * x return s
In this way, you do not need to pass in two parameters to calculate the square:
>>> Power (5) 25
Because the parameters of the function match in order from left to right, the default parameters can only be defined after the required parameters:
# Ok:def Fn1 (A, b=1, c=2): pass# error:def fn2 (a=1, b): Pass
Python Default Parameters