A function is a part that aggregates some statements together, they can run more than once in a program, the function can also calculate a return value, and can change the parameters as input to the function. These parameters are different every time the code is run. Writing an operation in the form of a function can make it a broad application tool.
Basic format:
def function Name: function Body return value
Define and Invoke
The definition function defines the function according to the preceding basic format, calling the function with the function name parentheses to invoke the function, and the parentheses can contain one or more parameters. These parameters are passed to the parameter name of the function head.
# definition def Test (x, y ): return x*y# call test (5,10)
function parameter Prerequisite parameters
The func (valule) function is called by location to match, and arguments cannot be omitted when the function is called.
Default parameter (keyword parameter)
The func (name=value) function, if not given arguments at the time of invocation, is passed by the value of the default parameter, and if the default parameter is re-assigned when the function is called, the original value is overwritten.
def func (name="Joe"): print(name) func ()> >>joefunc ("austinjoe"#func (name= "Austinjoe") It's also possible >>>austinjoe
Indefinite length parameter
- Func (*args) collects all positional-related parameters into a new tuple and assigns the tuple value to the variable args. * can match any length and number of parameters.
def func (*args): print(args) func (* (1,2,3,4))#func (1,2,3,4) This form is also available in the >>> (1, 2, 3, 4) func ([all-in-one], 'hello',' python ' )'hello'python'
2.func (**kwargs) is similar to the above, but it is a collection of parameters into a dictionary.
defFunc (**kwargs):Print(Kwargs) func (a=1,b=2)>>>{'b': 2,'a': 1}
Func(* *{' a ': 1,' B ': 2})
>>>{' a ': 1, ' B ': 2}
Unpacking parameters
In Python we can unpack the parameters with * and * *.
def func (a,b,c,d): print (a,b,c,d) args = (1,2,3,4 ) func ( *args) >>>1 2 3 4
def func (a,b,c,d): Print (a,b,c,d) args={'o': 1,'b': 2,'C ': 3,'d': 4}func (* *args)>>>1 2 3 4
Attention
Parameter types can be mixed, but must follow the following rules:
- In a function call, the arguments must appear in this order: positional arguments followed by any keyword argument, then *args, and finally followed by **kwargs.
- In the function header, the arguments must appear in this order: the default parameters are followed by the general parameters, if any, followed by *args, and finally **kwargs.
Anonymous functions: Lambda
A lambda is an expression that creates a function that can then be called, but returns a function instead of assigning the function to the variable name.
The General format is:
Lambda: Argument1,argument2 Argumentn:expression using arguments
Lambda x, y, z:x + y + zprint(f (2, 3, 4))>>>9
Lambda expressions are often used in conjunction with the map () and filter () functions, and we'll learn about them next.
Map (): Map in sequence
The map function applies the passed-in function to each element in a sequence object, and returns a list containing the result of the function call that was used.
L=list (Map ((Lambda x:x+2), [1,2,3,4])print(l)
>>>[3, 4, 5, 6]
L=list (Map (pow,[1,2,3],[5,6,7))print(l)>>>[1, 64, 2187]
Filter (): Filtering elements
The filter () function filters out some elements based on the test function.
L=list (Filter (lambda x:x>0), range ( -10,10))print(l)>>>[1, 2, 3, 4 , 5, 6, 7, 8, 9]
Reduce ()
The Y number of reduce () functions applies a function to each element and runs to the final result.
from Import Reduceresult=reduce ((Lambda x,y:x+y), [1,2,3,4])print(result) >>>10
Closures: function nesting (indirect function calls)
A closure is a function that is inside a function called a function, which is a nested function.
defMain ():Print("Hello World") defNest ():Print("I am a nested function! ") returnNest#The first form ofmain () ()>>>Hello World>>>I am a nested function! #The second form ofm=Main () m ()>>>Hello World>>> I'm a nested function!
Recursive functions
The use of recursive functions should be noted:
- The number of recursion is limited in python;
- The amount of memory occupied by the recursive function increases with the geometry;
- The recursive function must have a termination condition.
# sum a list def Sumtree (L): = 0 for in L: if not isinstance (x, List): + = xElse: + = sumtree ( x)return = [1, [1, 2, [6, 7], 3], 4, 5, [9, 8]]print(Sumtree (L)) >>>46
callback function
The execution of function A depends on the execution of a condition in function B, and function A is a callback function.
defMain (x):ifX>5: Print("callback function not executed!! ") Else: returnCallback ()defcallback ():Print("callback function Execution!! ") Main (10)>>>callback function not executed!! Main (4)>>> callback function Execution!!
Scope
Scope rule:
- The embedded module is a global scope;
- The scope of the global scope is limited to a single file;
- Each call to a function creates a local scope;
- Assigned variable names are local variables unless declared as global variables and non-local variables;
- All other variable names can be categorized as local, global, or built-in.
x=88def func (y): z=x+Y return zprint(func) # where x and function func are global variable names, and Y and Z are local variable names
Global statement
The global statement is used to declare one or more global variable names.
x =def func ( ):global X = A.func ()Print (X)>> > 99
nonlocal statements
When declaring a nonlocal variable name, the variable name must exist in the nested scope of the function, that is, they can only exist in a nested function, and cannot have a nested def in the first assignment creation.
defTester (START): state=Startdefnested (label): nonlocal StatePrint(label, state) state+ = 1returnNESTEDF=Tester (0)Print(F (' First'))>>>First 0Print(F ('Second'))>>>second 1Print(F ('Third'))>>>third 2
Python Basics (eight): Functions