First, the function
1. Function definition: function is a programming method of logical structure and process
Function Composition:
1 function definition methods in Python:2 defTest (x):3 "The function Definitions"4X+=15 returnx6 def: Defines a keyword for a function7 test: Name of function8 (): Internal definable parameters9 "": Document description (not necessary, suggest adding descriptive information to the function)TenX+=1: Generic code block or program processing logic One return: Defines the return value A -Function call run: can be with or without parameters
2. Functions and Procedures
Procedure: is a function that does not return a return value, strictly speaking, there is no procedure in Python, because no value in Python directly returns a none!
3. Benefits of using functions
(1), Code reuse
(2), maintain consistency, easy to maintain
(3), scalability
4. Parameters of the function
(1), Shape parametric the memory unit is allocated only when it is called, and immediately releases the allocated memory unit at the end of the call. Therefore, the formal parameter is valid only within the function. After the function call finishes returning the keynote function, the shape parametric can no longer be used
(2), arguments can be constants, variables, expressions, functions, and so on, regardless of the arguments are the type of variable, in the function call, they must have a certain value, in order to pass these values to the parameter. It is therefore necessary to use the method of assignment, input and so on to obtain the definite value of the parameter
def # x, y as formal parameter res = x**y return# 3,4 as argument print(a)
(3), Positional parameters and keywords (standard call: argument and parameter position one by one correspond; keyword call: position without fixing)
A, positional parameters, parameters must be one by one corresponding, lack of a no, more than one can not
b, keyword parameters, no one by one correspondence, lack of a no, more than one night not
C, positional parameters and keyword parameters when mixing, positional parameters must unload the keyword parameter left or it will be an error
defxianxin (x, Y, z): Res= x+3*y-2*ZreturnResa= Xianxin (8,1,2.3) Print(a)#6.4 defxianxin (x, Y, z): Res= x+3*y-2*ZreturnRes#typeerror:xianxin () takes 3 positional arguments but 4 were given#This error occurs when the parameter is 3 x, Y, z, and the argument is 4 when the function is called.#a = xianxin (8,1,2.3,1)#typeerror:xianxin () Missing 1 required positional argument: ' Z '#This error occurs when the parameter is 3 x, Y, z, and the argument is 2 when the function is called.A = Xianxin (8,1)Print(a)
(4), default parameters
1 defHandle (x,oraclename='ORCL'):2 Print(X,oraclename)3A = handle ('Hello World')#Oraclename is assigned when called, the default is ORCL4 Print(a)#output Result: Hello World orcl None5 #Why does Hello World orcl then output a none? Because there is no return value when defining the handle function, no return value is defined in Python6 #will return none by default;7 8 9 Ten defHandle (x,oraclename='ORCL'): One Print(X,oraclename) A returnTrue - #welcone To:python #True - Print(Handle ('Welcone to:', Oraclename ='Python'))
(5), parameter group
defTest (x,*y):Print(x)#1 Print(y)#(2, 3, 4, 5, 6) Print(Y[0])#2Print(Test (1,{2,3,4,5,6}))defTest (x,*y):Print(x)#1 #if a list or dictionary is passed in, place the list or dictionary directly as an element in a tuple Print(y)#([2, 3, 4, 5, 6],) Print(Y[0]) [2, 3, 4, 5, 6]Print(Test (1,[2,3,4,5,6]))
Note: The above is the entire list or dictionary as an element of the value to the parameter if I pass in a list, I just want to pass the elements in the list to the parameter.
1 def Test (x,*y):2 print(x) #13 Print#(1, 2, 3, 4)4 Test (1,*[1,2,3,4])
By adding a "*" directly to the incoming list argument, you can pass the element in the list to the parameter
Note: **kwargs:**{}, the elements inside the dictionary can be passed to the parameter
1 defTest (x,**Kwargs):2 Print(x)#x3 Print(Kwargs)#{' Y ': 2, ' Z ': 3}4Test (1,y = 2,z = 3)5 6 defTest (x,**Kwargs):7 Print(x)#18 Print(Kwargs)#{' Z ': 2, ' Y ': 3}9Test (1,**{'Z': 2,'y': 3})Ten One defTest (x,**Kwargs): A Print(x) - Print(Kwargs)#typeerror:test () takes 1 positional argument but 2 were given -Test (1,{'Z': 2,'y': 3})
*args:*[], you can pass the elements inside the list to the parameters, receive variable-length values, the main function is to use for the later extension, and the number of parameters that are not sure of the calling interface
def Test (x,*y):2 print(x) #13 print# (1, 2, 3, 4)4 test (1,*[1,2,3,4])
Note: Those two mixed, can not violate a large premise, positional parameters must be on the left side of the keyword parameters, or after the error, *args and **kwarg mixing is to follow this principle
defTest (x,*args,**Kwargs):Print(x)#1 Print(args)# Print(Kwargs)#(' A ', ' B ')Test (1,'a','b', y=1,z=1)#{' Y ': 1, ' Z ': 1}defTest (x,*args,**Kwargs):Print(x)#1 Print(args)#(1, 2, 3, 4, 5) Print(Kwargs)#{' Z ': 1, ' Y ': 2}Test (1,*[1,2,3,4,5],**{'Z': 1,'y': 2})
Second, local variables and global variables
1. Global Variables: global scope
Modifying global variables in a function modifier words: Global
1Name ='Zhuliye'2 defchange_name ():3 Globalname4Name ='Zhuyintai'5 Print('My name is', name)#My name is Zhuyintai6 Change_name ()7 #When the Change_name function is called, the value of the global variable name is "Zhuyintai"8 Print(name)#Zhuyintai
2. Local Variables: local scope
Nolocal modifier is the upper-level variable
3, function is variable--forward reference
Third, function recursion
1. Dead Cycle
First look at the following code: Run the following code, error: "Into the Dead loop", because the function calls itself when there is no definite end of the condition, so there is a dead loop, causing memory overflow
1 def Calc (n): 2 Print (n) 3 Calc (n)4#recursionerror:maximum recursion depth exceeded while calling a Python Object
2, function recursion characteristics:
(1), function recursion
Inside a function, other functions can be called, if you call a function directly or indirectly called itself is a function recursive
(2), function recursion characteristics
A, there must be a definite end condition, otherwise there will be a cycle of death
b, each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
c, 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 reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.
Stack Explanation: http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html
Tail recursion optimization: http://egon09.blog.51cto.com/9161406/1842475
Iv. anonymous function lambda
1. Lambda function format: Lambda parameter: expression
Example: Lambda x:x+1
1 Lambda x:x**22 func (3)Thelambda function is a string of memory addresses when not called;4 #lambda functions generally do not exist alone;5print#<function <lambda > at 0x000001641c1029d8>6print#
2. Lambda function with multiple parameters
1 #Print (lambda name: ' name ' + ' _SB ')2 #res = lambda name:name+ ' _SB '3 #Print (lambda name: ' name ' + ' _SB ') #<function <lambda> at 0x0000019a8f812d90>4 #Print (res (' zhangssn ')) #zhangssn_sb5 6 7 #res1 = lambda x,y,z:2*x+3*y-z8 #Print (Res1 (10,2,-1)) #27 or follow the principle of function positional parameters9 #Print (Res1 (1,2,z=3)) #5 position parameters and keyword parametersTen OneRes2 =LambdaX, Y, Z:(x+1,y+2,z+3) A Print(Res2 (10,2,4))#(one, 4, 7)
Five, function-type programming
Three methods of programming
1, object-oriented programming;
2, Function-type programming;
3, object-oriented programming;
1. Process oriented
Find a solution to the problem, follow a fixed process to simulate the problem-solving process
Example:
A, search target, user input (spouse request), according to the requirements to the data structure (dictionary) to retrieve the people who meet the requirements
b, vindicate, vindicate successfully entered 3, otherwise enter 2;
C, Love, Love successfully entered 4, otherwise return 1;
D, see parents, parents agree to enter 5, parents say he is your long-lost sister, return 1;
E, marriage
1 def Res (x, y): 2 # 1 3 # 2 4 Res3 = res2*2#35 return res36 Res (2,1) 7Print(res (2,1))
2. Function-type programming:
Functional programming: function = function of programming language definition + function of mathematical meaning
function is to use programming language to implement mathematical functions. The object in this function is immutable, either the parameter is a function, or the return value is a function, there is no for and while loop, all loops are implemented by recursion, no variable assignment (that is, without the variable to save the state), no assignment is not changed.
(1), characteristics
A, immutable data--do not use variables to save the state, do not modify the variable
B, the first class of objects-the function name can be passed as a parameter, the return value can be a function name
c, tail call optimization (tail recursion)
3. Object-oriented
Functions of Python