Elements-of-Python_04_Function

Time:2021-3-27

(including functions, recursion, lambda, scope, etc.)

1. Function

1.1 function overview

Function is a kind of programming method to structure and process program logic, which is used to encapsulate a specific function and represent a function or behavior. A function is a statement block that can be executed repeatedly. It is the most basic program structure with high reuse and low redundancy. It can be called many times at one time. [high reuse, low redundancy]
Functions can be simply divided into built-in functions and custom functions. Built in function is a function that has been written in Python or imported module, and user-defined function is a function defined by a regular and reusable code, which is a manageable part in the program. [process breakdown]

1.2 common built-in functions

Many convenient functions are integrated in Python, which are provided in the form of functions.Official documents

1.3 user defined functions

Custom function, that is to create a function, with some uses, can use a code block. User defined functions are the same as built-in functions: they are called by expressions, and some parameters are input to get a result.
Defining functions follows the following rules:

  1. The function has 0 inputs and 1 or more outputs.
  2. Use def keyword to define function; return or yield to return, no return, default return none; implement function in function body.
  3. The concrete form is: def Add a user-defined function name to define the name of the function, and take the name yourself, so as to achieve literal meaning; then add parentheses, in which the ordinary parameters are added first, then the default parameters are added, and finally the variable parameters are added; add a colon after the parameter list, and the next line indents the function body, that is, the part that runs during each call; the function body needs to have one or more return values (if not) The default value is none.
    自定义函数基本格式

1.3.1 definition of user defined function

User defined functions are defined by using the keyword def (short for define). After def, you need to write a function name. The function name should be literal and conform to the naming rules (beginning with a letter, only containing the letter underline and numbers, not keywords). After the function name, you need the parameters (ordinary parameters, default parameters, variable parameters) of the function. Then there is the colon and the function body written in indent below. The function body needs to have a return value (default return none if there is no return value). When calling, once return means the end of the call. Furthermore, the return value can be of any type, but only one object can be returned.

#Input parameter day month year, return and today difference a few days
import time
def isLeapYear(y):
    if y%4==0 and y%100!=0 or y%400==0 :
        return True
    else :
        return False

def daysGone(m,flag):
    Listgone1 = (365, 0, 31, 59, 90, 120, 151, 181, 212, 224, 327, 303, 334) # ordinary year
    Listgone2 = (366,0,31,60,91121152182213244274305335) # leap year
    if flag :
        return listGone2[m]
    else :
        return listGone2[m]

def date_apart(d1,m1,y1):
    lastest = [int(time.strftime("%d")),int(time.strftime("%m")),int(time.strftime("%Y"))]
    daysofMonth = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
    leap = total  = 0
    for i in range(y1+1,lastest[2],1):
        total += 365
        if i%4==0 and i%100!=0 or i%400==0 :
            leap += 1
    total += leap
    total += daysGone(lastest[1],isLeapYear(lastest[2])) + lastest[0]
    total += 365 + isLeapYear(y1) - daysGone(m1,isLeapYear(y1)) - d1
    if y1==lastest[2] : total -= 365
    return total

print(date_apart(17,8,1926))

From the above function, we can see that:
① Function can be used as an argument to another function
② The type of return value can be varied, but it will stop running until return
③ Other functions can be called in the function body

1.3.2 about function parameters

Function parameters can be divided into actual parameters (common parameters, default parameters) and variable parameters (location parameters, named parameters). When defining: the actual parameter must be in front of the variable parameter. It is recommended that the default parameter be placed after the ordinary parameter. The resulting parameters can appear or not appear in the function body (that is, if you want to use the parameters, it’s up to you). Call time: when inputting parameters, you can input them one by one according to the order, or in the form of [parameter name = assigned value], not in the order. If the default parameter is not assigned, it is entered according to the default value. Variable parameter is the indefinite number of parameters into the function.
For variable parameters, any name can be preceded by one or two * signs, which are written at the end of the parameter list in the order of single * first and double * second. Commonly used groups are [* args, * * kargs] and [* vars, * * kvars]. *The symbol represents the extra list and tuple to be received, and the * * symbol represents the map and dictionary to be received. In other words, ① named parameters in the form of a = B (key value pair) in the parameter list are passed into * * kargs; ② positional parameters in the form of a, B, C (tuple) in the parameter list are passed into * args.

If the actual parameters are not enough, it will borrow parameters from the positional parameters (variable parameters with a single * sign); when the positional parameters are not borrowed, ask the named parameters (variable parameters with two * signs) to borrow parameters (key value pairs), but the key must be equal to the name of the actual parameters before the value will be passed into the actual parameters. On the other hand, if there are more parameters in the position of the actual parameter, the key value pair will be filled in the named parameter to become a dictionary, and the others will be filled in the position parameter in order to become tuples. In addition, for variable parameters in the parameter list, the positional parameters must be assigned before the named parameters.
When calling a function, you can use * and * * even if all parameters are defined. *The * sign is used to expand the types of multiple elements. The difference is that the * sign only displays the keys (), and the * * sign displays the key value pair items().

About default parameters:
Once the default parameter is generated, the user does not change it manually, and the default parameter will not change. For example, def add (a, B, C =], once a non empty list [1] is passed in to C for the first time, C will be assigned to [1], and then C = [1] instead of [1] will be used by default. Similarly, if the default parameter passes in a random number, it will be random for the first time, and then it will always take the random value of the first time. Therefore, random values are needed in the parameters, which must be passed in with actual parameters instead of default parameters.

def tt(a,b,z,*c,**d):
    print(a)
    print(b)
    print(z)
    print(c)
    print(d)

TT (* range (1,15,3)) # the actual parameters are not enough, and the position parameters are added with the actual parameters
print("---------------------------")
TT (1, * range (2,3), * * {"Z": 20, "BBB": 23}) # the actual parameters and positional parameters are not enough, and the named parameters are added
print("---------------------------")
TT (1,3,5,7,9,11,13,15, f = 10, x = 16, k = PPP) # more real parameters, put in variable parameters

运行结果

1.3.3 function body

In the function definition, the indented part is the function body, which is mainly responsible for realizing the function function and returning the value. The function body starts with a colon and is indented. If you use the document string (three colons) in the first line, it will be regarded as writing the description document of the function. In the function body, you can write almost all statements, or even define another function. If you just write a function name and the function body has not been decided, you can use the pass keyword to occupy the space first. The function body should contain a return value, which is returned with the return or yield keyword. If there is no return value, or if only return is written without variables, the default value is none. Function body (including return value) can call other functions or itself.

1.3.4 return value

Why do you need to return when you have a print statement to output directly? This is because the function only solves one problem, not the whole thing. Taking the above example, I want to know whether it is a leap year, and whether the output is useless, but returning a true can be used as an input parameter of subsequent functions.
Return and yield can be used to return the required variables. The return value is used as the output of the function when it is called.
What is the difference between return and yield? Return output all at one time and end after output; yield is used together with next or send to output one step at a time and output the next step after next call. To put it simply, return is always in the end, and yield is blocked in the sentence of yield. Use the next call to start from this sentence of yield and then block it again.
return VS yield
As can be seen from the results in the figure above, return directly outputs the value of the first loop in the first loop and ends; next + yield will not run until it runs to yield for the first time. After being activated by the next next next, it will run from the last yield and will not run until the next yield. This is yield.

1.4 function call

After the user-defined function is defined, it can be called. Only when it is called, will it check whether the custom function is written correctly. When calling, you can write the required parameters of the user-defined function to the parameter list after the function name. You can use the location parameter and naming parameter methods. You need to pay attention to the number and the location of the location parameter. In addition, for help documents, use help (name) (without parameter name). The result of the function is the return value of the function.

1.5 recursion

In function definition, you can also call other functions in function body. To put it simply, if you call yourself or several functions call each other, it is called recursion. Strictly speaking, what is suitable for recursion is that it can decompose the problem into smaller problems with the same solution as the original problem. 】There are some preconditions for successful recursion: ① with the deepening of recursion depth (the number of times becomes more and more), the problem should be more and more simple; ② there should be a judgment (recursion exit) in recursion, which returns the return value that no longer needs to be called when the problem is the simplest; ③ the number of recursion is not unlimited, and if you do not set recursion 1000 times or so, the stack will overflow. [in a certain number of times, the depth increases and the scale decreases, and finally it ends]
Recursive features: simple to write, easy to understand, no complex nesting, easy to stack overflow, multiple calls time-consuming, low efficiency.
Data, data structure and problem description are recursive, so we should think of recursion.
There are two ways of recursion: first, to execute the next time and use the previous result (recursion); second, to terminate, we need the condition of the previous layer (backtracking).

1.6 lambda expression

Lambda expression is an anonymous function used to simplify the workload of programmers. Features: allows you to quickly define a single line of the minimum function. Its only grammatical form is:
In the formula, the variable before the colon is the parameter list in the function, and the expression after the colon is the return value in the function. Lambda expressions seem simpler and more pythonic to use, but their internal logic is the same as defining a function, and they do not support multi branch languages and exception handlers. Usage, its input is the parameter list, the output is the result of the return value. It can be used with filter, sorted, map, reduce and other functions.

1.7 help document

When using a function, even if the name is too literal, you still need more support, such as help documents or instructions. In the custom function, as long as you use the document string, you can easily write the help document.
Specifically, to write a help document for a function, you need to define the function and input the first line of the function body with a string (one line with ordinary quotation marks, and multiple lines with three quotation marks). The whole document string will be regarded as a help document. When calling, use the help (name) function to view. You only need to write the function name, not the parameter list.

1.8 scope

Let’s talk about assignment first. Assignment is to connect the variable name you take with this object. That is to say, the assignment is that the name points to a new object, rather than changing the object directly through the name.
What if the variables in your own function and script main function have the same name? If you only refer to external variables, look for the name in different scopes in legb order.
Order: localclosing function globals__ builtins__ (that is: the internal nested function contains the global scope of the internal nested function itself and the built-in scope), the priority of the scope ranges from high to low, and the scope ranges from small to large. Among them:

  • Locales: function internal namespace, including local variables and formal parameters
  • Enclosing function: the namespace of an external nested function
  • Globals: the namespace of the module where the function definition is located
  • __ builtins__ : the namespace of the built-in module

The built-in scope is pre-defined and can be used in the__ builtins__ Module. These names are mainly keywords, such as open, range, quit, etc.; the global scope is at the file / module level, and the variables at the top level in each. Py file are variables within the global scope; the local scope is the scope of the function, because the function can be nested, and the nested inner function has its own inner scope; the nested function has its own inner scope The local scope of a number belongs to the inner function, not the outer function.
When a command needs to use an object, it will first find out whether there is an object in the layer function according to the legb order.

As can be seen from the above figure, in print 1 and 4, the global variable x is printed. After calling K, the internal namespace of the function in K is printed, while m cannot be read by the script. To explain, variables defined in parameter lists and functions are called local variables, which can only be called locally, and the value of a higher level variable cannot be changed. A higher level can only call functions defined by its own peers, not functions defined in functions.

Since the change of the parameters passed in the parameter list cannot change the global variables, does this mean that the function can only change the global variables through the return value? No, you can change the value of a global variable from a function by introducing the global keyword. As shown in the figure:

1.9 function design concept

Functions should strive to be independent of the outside, using parameters as input and return as output; using global variables only when it is really needed; the goal of functions should be single and unified; each function should be relatively small; variables in other module files should not be changed as far as possible.

1.10 function type check

After Python 3.5, function type checking function has been added. The colon and type are added after the parameters listed in the parameter list of the defined function to specify the input type of the formal parameters in the parameter list, and the return value type is specified with the symbol -.

def sum(a:int,b:[int])->float:
    for i in b:
        c += i
    return a*1.0+c

In the above code definition, it is required that the type of parameter a must be int, the type of parameter B must be list, each element in B must be an integer, and the type of return value must be floating-point decimal. If the type of input parameter and formal parameter is not the same when calling the function, a warning will be given in IDE, but the normal operation of the function will not be affected.

1.11 method naming

In pyhton, you can not only name attributes, such asa=bMethods can also be named, such asc=math.sqrtIn this way, C and math.sqrt Equivalent,print(c(4))It will output 2.0.

Recommended Today

Use of mock framework MOQ

Use of mock framework MOQ Intro MOQ is a very popular mock framework in. Net. Using the mock framework, we can only test the code we are concerned about, and use the mock object to configure the expected behavior of dependent services for dependencies. MOQ is based onCastleBased on the dynamic agent technology, the types […]