1. Introduction to Functions
Why do you have a function? Because when writing code in peacetime, if there is no function, then there will be a lot of duplicate code, so the code reuse rate is relatively low ... And this kind of code is also very difficult to maintain, in order to solve these problems, there is a function, to be used to encapsulate some of the frequently occurring code, so that you can call this code in any place to call this function is OK.
function definition: A function refers to the collection of a set of statements by a name (function name) to encapsulate, to execute this function, just call their function name to
Characteristics:
Code reuse
Maintain consistency
Scalability
2. Creation of functions
In Python, the format of a function definition is as follows:
def function name (formal parameter): Inner code block of function body
The function's call uses the function name (argument) to invoke the function.
The naming conventions for function names are the same as the naming conventions for variables:
The function name must begin with an underscore or letter and can contain any combination of letters, numbers, or underscores. Cannot use any punctuation marks;
Function names are case-sensitive.
The function name cannot be a reserved word.
The difference between a formal parameter and an argument:
function at the time of definition, the function name after the parentheses can be added to the parameters, these parameters are called formal parameters, parameter: As the name implies is the formal parameter, just a code name.
An argument is a parameter in parentheses following the function name at the time the function is called, and the formal parameter and argument need to correspond to one by one, otherwise the calling function will error.
3. Function parameters and return values
Before we refer to the formal and actual parameters of the function, the parameter pairs should be as follows:
Required Parameters
Keyword parameters
Default parameters
Indefinite length parameter *args
Indefinite length parameter **kwargs
1. Required Parameters:
Must arguments must be passed into the function in relation to the corresponding relationship, the arguments passed at the function call must correspond to the parameter one by one when the function is defined, not many or fewer, and the order is consistent.
Give me a chestnut:
def f (name,age): print (Name,age) f ("Xiaoming", 18)
2. Keyword parameters
The keyword argument is the concept inside the argument, and when the function is called, it is declared that a parameter belongs to a keyword. Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.
Give me a chestnut:
def f (name,age): print (Name,age) f (name= "xiaoming", 18)
3. Default parameters
The default argument is that when the function is declared, you can specify a default value for a parameter, which is called the default value parameter. If the default parameter does not receive the corresponding argument when the function is called, the default value is assigned to the parameter.
Give me a chestnut:
def f (name,age,sex= "male"): print (Name,age,sex) f (name= "xiaoming", 18)
In this way, the default parameter male will be assigned to sex.
4. Indefinite length parameter *args
In Python, when a function is declared, arguments can be used (* variable name) to accept parameters of indeterminate length, but in Python it is customary to use *args to accept indefinite long arguments, so that the arguments passed when the function is called can be of indefinite length. After args accepts indeterminate parameters, they are placed inside a tuple and can be accessed by args to obtain these indeterminate length parameters.
Give me a chestnut:
def f (*args): print (args) f ("Xiaoming", "male")
A tuple is printed, which contains three elements ("xiaoming", "male").
5. Indefinite length parameter **kwargs
But the above args can only receive unnamed parameters, what if there is an indefinite length parameter similar to the keyword parameter? Python Uses (* * variable name) to receive variable-length named arguments. Similarly, Python also uses **kwargs to receive indefinite long named parameters. After the Kwargs receives the variable length parameters, the parameters are placed in a dictionary and the corresponding parameter values can be obtained by key.
Give me a chestnut:
def f (**kwargs): print (Kwargs) f (name= "xiaoming", age=18,sex= "male")
After describing these parameters, the next step is to describe the mixed use of these parameters:
What if a function uses all the kinds of parameters above? In order to make no ambiguity, Python specifies that if there are multiple parameters mixed, the following sequence of rules are used:
def f (must parameter, default parameter, *args,**kwargs):
Pass
If both args and Kwargs are present, args is on the left
The default parameter is to the right of the required parameter, to the left of *args
The position of the keyword parameter is not fixed (PS: The keyword parameter is not determined at the time of the function definition)
So, if you have a list that you want to pass into a function that goes into a variable-length unnamed parameter, you can precede the list with an * implementation, and if you want to pass a dictionary into a function that has a variable-length named argument, you can precede the dictionary with * *
Give me a chestnut:
def f (*args,**kwargs): print (args) for i in Kwargs: print ("%s:%s"% (I,kwargs[i])) F (*[1,2,3],**{"a" : 1, "B": 2})
return value of the function
To get the result of the function execution, you can return the result using the return statement
Attention:
The function will stop executing and return the result as soon as it encounters a return statement, or it can be understood that the return statement represents the end of the function if no return is specified in the function, the function returns a value of None
Return multiple objects, the interpreter assembles the multiple objects into a tuple as a result of one overall output.
4.LEGB Scopes
The scope in Python is divided into 4 scenarios:
l:local, local scope, which is the variable defined in the function;
E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but not the global;
G:globa, a global variable, is a variable defined at the module level;
B:built-in, the variables inside the system fixed module, such as int, ByteArray, etc. The order of precedence for a search variable is: scope local > Outer scope > Global >python Built-in scope in the current module, that is, LEGB.
Local and enclosing are relative, and enclosing variables are local to the upper level.
In Python, only modules, classes, and functions (Def, Lambda) introduce new scopes, and other blocks of code (such as if, try, for, and so on) do not introduce new scopes.
Modification of variables (error modification, often out of the question in the face):
X=6 def f2 (): print (x) x=5 F2 () # The reason for the error is that when print (x) is found, the interpreter will find it in the local scope, the x=5 will be found (the function has been loaded into memory), but X is used before the declaration, so error: # Local Variable ' x ' referenced before assignment. How to prove to have found x=5? Simple: Comment out x=5,x=6 # error: Name ' x ' is not defined #同理 x=6 def f2 (): x+ =1 #local variable ' x ' referenced before assignment. F2 ()
Global keyword
The Global and nonlocal keywords are used when the internal scope wants to modify the variables of the outer scope, and when the modified variable is on the global scope (the globally scope), use global first to declare the code as follows:
Count = Ten def outer (): Global Count print (count) count = ( count) outer ()
nonlocal keywords
The variables declared by the Global keyword must be on the global scope, not nested scopes, and when you want to modify the variables in the nested scope (enclosing scope, outer non-global scope), then you need to nonlocal the keyword.
def outer (): count = ten def inner (): nonlocal count count = print (count) inner () print (count) outer ()
Summary
Variable lookup order: LEGB, scope local > Outer scope > Global >python Built-in scope in the current module;
Only modules, classes, and functions can introduce new scopes;
For a variable, the inner scope declares the outer variable first, and the external scope is used without declaring it directly;
Internal scope to modify the value of an external scope variable, a global variable uses the global keyword, and the nested scope variable uses the nonlocal keyword. Nonlocal is the python3 new keyword, with this keyword, you can achieve the perfect closure.
5. Special functions
Recursive function definition: A recursive function calls itself within a function
Sometimes when solving some problems, logic is more complex, at this time can consider using recursion, because the use of recursive functions, logic is clearer, can solve some of the more complex problems. However, there is a problem with recursive function is that if the number of recursive calls themselves more, will make the computation speed is very slow, and in Python the default recursive call depth is 1000 layer, more than this layer will lead to "burst stack" ... Therefore, it is advisable not to use recursion when possible without recursion.
Give me a chestnut:
def factorial (n): # Use loop to implement sum sum=1 for i in range (2,n+1): sum*=i return Sum print (factorial (7)) def recursive_factorial (n): # Use recursive implementation to sum return (2 if n==2 else n*recursive_factorial (n-1)) print (recursive_ Factorial (7)) def Feibo (n): # using recursion to implement Fibonacci that tangent sequence if n==0 or N==1:return n else:return Feibo (n-1) +feibo (n-2) print (Feibo (8)) def FEIBO2 (n): # Use Loop to implement Fibonacci that tangent sequence before,after=0,1 for i in range (n): before,after=after,before+after return before print (Feibo2 (300))
Advantages of recursive functions: simple definition, clear logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.
Recursive properties:
Must have a definite end condition
Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. )
6. Functional programming
I don't understand much about functional programming, but there are 4 more important built-in functions in Python that can be used in combination to make programming much more efficient.
1 filter (function, sequence) str = [' A ', ' B ', ' C ', ' d '] def fun1 (s): if s! = ' A ': return s ret = filter (FUN1, str) p Rint (List (ret)) # RET is an iterator object
Executes function (item) on item in sequence and returns an iterator that executes the result of true to a filter object. Can be seen as a filter function.
2 map (function, sequence)
str = [1, 2, ' A ', ' B '] def fun2 (s): return S + "Alvin" ret = map (fun2, str) print (ret) # Map Object iterator print (list ( RET) # [' Aalvin ', ' Balvin ', ' Calvin ', ' Dalvin ']
Executes function (item) on item in sequence and returns the execution result into a Map object iterator. Map also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:
def add (x, y): return x+y print (list (map (add, range, range (10)))) ##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
3 reduce (function, sequence, starting_value)
From functools import reduce def add1 (x, y): return x + y print (Reduce (ADD1, range (1, 101)) # # 4950 (Note: 1+2+...+99) Print (Reduce (ADD1, range (1, 101), 20)) # # 4970 (Note: 1+2+...+99+20)
The function is called on an iteration of the item order in sequence, and if there is starting_value, it can also be called as an initial value.
4 Lambda
The comparison between the normal function and the anonymous function:
#普通函数 def add (b): return a + B print Add (2,3) #匿名函数 add = lambda a,b:a + b print Add (2,3) #======== output ===== ====== 5 5
The naming convention for anonymous functions, identified by the LAMDBA keyword, and the left side of the colon (:) indicates that the function receives the parameter (a, b), and the right side of the colon (:) represents the function's return value (A+B).
Because LAMDBA does not need to be named when it is created, it is called an anonymous function