This article brings you the usage and key points to note about the default values of python function parameters. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
The most useful form is to specify a default value for one or more parameters. The function thus created can be called with fewer arguments than allowed when defined, for example:
def ask_ok(prompt, retries=4, reminder='Please try again!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise ValueError('invalid user response') print(reminder)
This function can be called in several ways:
Give only the required Parameters: <span class="pre">ask_ok('Do <span class="pre">you <span class="pre">really <span class="pre">want <span class="pre">to <span class="pre">quit?')<br/></span></span></span></span> </span></span>
Give an optional parameter: <span class="pre">ask_ok('OK <span class="pre">to <span class="pre">overwrite <span class="pre">the <span class="pre">file?', <span class="pre">2 )<br/></span></span></span></span></span></span>
Or give all parameters: <span class="pre">ask_ok('OK <span class="pre">to <span class="pre">overwrite <span class="pre">the <span class="pre">file?', <span class="pre">2, <span class="pre">'Come <span class="pre">on, <span class="pre">only <span class="pre">yes <span class="pre">or <span class="pre">no!')</span></span></span></span></span></span></span></span></span></span></span></span>
in<span class="pre"></span> keyword. It can test whether a sequence contains a certain value.
definition process, so
i = 5 def f(arg=i): print(arg) i = 6 f()
Important warning: The default value will only be executed once. This rule is important when the default value is a mutable object (Python lists, dictionaries, and most class instances). For example, the following function will store the arguments passed to it on subsequent calls:
def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3))
[1] [1, 2] [1, 2, 3]
def f(a, L=None): if L is None: L = [] L.append(a) return L
The above is the detailed content of Usage and key points to note about the default values of Python function parameters. For more information, please follow other related articles on the PHP Chinese website!