Function
Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions
- Process oriented: Write base code from top to bottom according to business logic
- Function: A function code is encapsulated in a function, it will not need to be repeated later, only the function can be called
- Object-oriented: classify and encapsulate functions to make development "faster, better and stronger ..."
Characteristics:
- Reduce duplicate code
- Make programs extensible
- Make the program easy to maintain
1. Process oriented
def Work (POST): ... Print >>> work ("it") it
Process oriented
2. Object-oriented
def num (x, y): ... return x +>>> num (2,3)5
Object Oriented
Process-oriented versus object-oriented: process-oriented is a matter of "How to Do", object-oriented is one thing "who should do";
1. function parameters and Local variables
A parameter variable allocates a memory unit only when it is called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. After the function call finishes returning the keynote function, the shape parametric can no longer be used;
arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. Therefore, it is necessary to use the assignment, input and other methods to get the parameters to determine the value;
2. Parameter definition
The parameters in the function are divided into:
- Default parameters
- Key parameters
- Non-fixed parameters
Default parameters
defStu_register (name,age,country,course=None):Print("----Registered Student information------") Print("Name:", name)Print("Age :", age)Print("Nationality:", Country)Print("Course:", course) Stu_register ("Patrick"," at","China")
Course=none as default parameter
Key Parameters
Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, But remember a requirement is that the key parameters must be placed after the position parameter.
defStu_register (name,age,country,course=None):Print("----Registered Student information------") Print("Name:", name)Print("Age :", age)Print("Nationality:", Country)Print("Course:", course) Stu_register ("Patrick", age=" at", country="China")
Non-fixed parameters
*args represents any number of nameless arguments, which is a tuple;**kwargs representing the keyword argument, which is a dict.
defFun (*args, * *Kwargs):Print('args =', args)Print('Kwargs =', Kwargs)Print('###')if __name__=='__main__': Fun (1,2,3,4) Fun (a=1,b=2,c=3) Fun (1,2,3,4, a=1,b=2,c=3) Fun ('a', 1, None, A=1, b='2', c=3)
The result of the execution is:
args = (1, 2, 3, 4) Kwargs= {}###args =() Kwargs= {'C': 3,'a': 1,'b': 2}###args = (1, 2, 3, 4) Kwargs= {'C': 3,'a': 1,'b': 2}###args = ('a', 1, None) Kwargs= {'C': 3,'a': 1,'b':'2'}###
Note: When using both *args and **kwargs, the parameter column must be *args before **kwargs, such as foo (a=1, b= ' 2 ', c=3, a ', 1, None,) and will prompt syntax error "SyntaxError: Non-keyword arg after keyword arg ".
function return value
- The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function
- If return is not specified in the function, the return value of this function is None
defStu_register (name,age,country,course=None):Print("----Registered Student information------") Print("Name:", name)Print("Age :", age)returnName,agePrint("Nationality:", Country)Print("Course:", course) Stu_register ("Patrick", age=" at", country="China")
Execution Result:
D:\python3.5\python.exe d:/python/py14day3/day3_def.py----Registered Student information------23
Global and local variables (globals)
A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.
Analysis of recursion principle
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
Recursive properties:
1. There must be a clear end condition
2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion
3. 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, each time into 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.
def Calc (n): ... Print (n) ... if int (n)/2 = =0: ... return n . ... return calc (int (n/2>>> calc)2010521
Anatomy of an advanced function
A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.
def Add (x,y,f): ... return f (x) +>>> res = Add (3,-6, ABS)print(res)9
Python function application