Learning python (eight)-functions

Python also supports custom functions, that is, a regular, reusable code is defined as a function, so as to achieve the purpose of writing once and calling multiple times. That is, it allows us to encapsulate (package) the commonly used code in a fixed format into an independent module, as long as we know the name of this module, we can reuse it, and this module is called a function. In fact, the essence of a function is a piece of code that has a specific function and can be reused. This piece of code has been written in advance. This code can be called directly by the good name.

But one thing to note is that, like functions in other programming languages, Python functions support receiving multiple (≥0) parameters. The difference is that Python functions also support returning multiple (≥0) values.

1. Function definition

Defining a function, that is, creating a function, can be understood as creating a tool with certain uses. The definition function needs to be realized with the def keyword. The specific syntax format is as follows:

def function name (parameter list):
    //Multi-line code to achieve a specific function
    [return [return value]]

Among them, the parts enclosed in [] are optional parts, which can be used or omitted. Function name: In fact, it is an identifier that conforms to Python syntax, but readers are not recommended to use simple identifiers such as a, b, and c as the function name. The function name should best reflect the function of the function (such as my_len, above) That means our custom len() function). Formal parameter list: Set how many parameters the function can receive. Multiple parameters are separated by commas (, ). [return [return value]]: as an optional parameter of the function as a whole, it is used to set the return value of the function. In other words, a function can have a return value or no return value. Whether it needs to be determined according to the actual situation. The return statement in a function can directly return the value of an expression.

Under normal circumstances, the function form with parameters is selected when defining a function. The function of function parameters is to pass data to the function so that it can perform specific operations on the received data. When using functions, formal parameters (referred to as "formal parameters") and actual parameters (referred to as "actual parameters") are often used. Both are called parameters. The difference between them is: Formal parameters: When defining a function, the function The parameters in parentheses after the name are formal parameters; actual parameters: When calling a function, the parameters in parentheses after the function name are called actual parameters, which are the parameters given to the function by the caller of the function. According to the different types of actual parameters, the transfer methods of function parameters can be divided into two types, namely value transfer and reference (address) transfer: value transfer: applicable to immutable types of actual parameters (string, number, tuple) ; Reference (address) transfer: Applicable to the variable type (list, dictionary) of the actual parameter; the difference between value transfer and reference transfer is that after the function parameter is passed by value, if the value of the formal parameter changes, the actual parameter will not be affected. The value of the parameter; and after the function parameter continues to be passed by reference, if the value of the formal parameter is changed, the value of the actual parameter will also change.

Positional parameters, sometimes called mandatory parameters, mean that the actual parameters must be passed to the function in the correct order. In other words, the number and position of the actual parameters passed in when the function is called must be the same as when the function was defined. To call a function, the number of actual parameters specified must be the same as the number of formal parameters (passing more and less will not work), otherwise the  Python  interpreter will throw a TypeError exception and prompt that the necessary positional parameters are missing. When calling a function, the position of the actual parameter passed in must correspond to the position of the formal parameter one-to-one, otherwise the following two results will be produced: (1) Throw a TypeError exception (2) The result produced does not match expectations

Keyword parameters refer to the use of the name of the formal parameter to determine the value of the input parameter. When specifying the actual parameter of a function in this way, it is no longer necessary to be exactly the same as the position of the formal parameter, as long as the parameter name is written correctly. Therefore,  the parameter names of Python functions should have better semantics, so that the program can immediately clarify the meaning of each parameter passed into the function.

Python defines functions with default value parameters, and the syntax format is as follows:

def function name (..., formal parameter name, formal parameter name = default value):
             code block

When using this format to define a function, the formal parameters specified with default values ​​must be at the end of all parameters without default values, otherwise a syntax error will occur. In Pyhton, you can use "function name.__defaults__" to view the current value of the default value parameter of the function, and the return value is a tuple.

In  Python  , there is a special constant None (N must be capitalized). Unlike False, it does not mean 0, nor does it mean an empty string, but means that there is no value, which is a null value. The null value here does not mean an empty object, that is, None is different from [] and "": None has its own data type, as you can see, it belongs to the NoneType type. It should be noted that None is the only value of the NoneType data type (other programming languages ​​may call this value as null, nil, or undefined), that is, we can no longer create other NoneType variables, but you can assign None to any variable. If you want something stored in a variable not to be confused with any other value, you can use None. In addition, None is often used for asserts, judgments, and situations where the function has no return value. For example, in the previous chapters, we have been using the print() function to output data. In fact, the return value of this function is None. Because its function is to display text on the screen and does not need to return any value at all, print() returns None.

In addition, for all function definitions that do not have a return statement, Python will add return None at the end, and use the return statement without a value (that is, only the return keyword itself), then it will return None.

In Python , when you create a function with the def statement, you can use the return statement to specify the value that should be returned, and the return value can be of any type. It should be noted that the return statement can appear multiple times in the same function, but as long as one is executed, the execution of the function will be ended directly. If the program needs multiple return values, you can either wrap multiple values ​​into a list and return them, or return multiple values ​​directly. If the Python function directly returns multiple values, Python will automatically encapsulate the multiple return values ​​into tuples, and the return values ​​are separated by commas.

The scope of the variable defined inside the function is also limited to the inside of the function, and cannot be used outside the function. We call such variables as local variables (Local Variable). You should know that when a function is executed, Python will allocate a temporary storage space for it, and all variables defined inside the function will be stored in this space. After the function is executed, this temporary storage space will be released and reclaimed immediately, and the variables stored in this space will naturally no longer be used. As you can see, if you try to access the internally defined variables outside the function, the Python interpreter will report a NameError error and prompt us that the variable to be accessed is not defined. This also confirms that when the function is executed, the internally defined variables will be Was destroyed and recycled. It is worth mentioning that the parameters of a function are also local variables and can only be used inside the function.

In addition to defining variables inside functions, Python also allows variables to be defined outside all functions. Such variables are called Global Variables. Unlike local variables, the default scope of global variables is the entire program, that is, global variables can be used either outside or inside each function.

In some specific scenarios, we may need to obtain all variables in a certain scope (global scope or local scope). Python provides the following three methods: (1) globals() function: globals() function is Python's Built-in function, it can return a dictionary containing all variables in the global scope. For each key-value pair in the dictionary, the key is the variable name and the value is the value of the variable. (2) The locals() function: The locals() function is also one of Python's built-in functions. By calling this function, we can get a dictionary containing all the variables in the current scope. The so-called "current scope" here means that calling the locals() function inside the function will get a dictionary containing all local variables; and calling the locals() function in the global template has the same function as the globals() function. (3) vars(object): The vars() function is also a Python built-in function, and its function is to return a dictionary composed of all variables within the specified object range. If the object parameter is not passed, vars() and locals() have exactly the same effect.

Python supports defining functions inside functions, and such functions are also called local functions. Like local variables, local functions can only be used within the scope of the function in which they are located by default. If the local function does not return a local function, the available range of the local function is limited to the function inside; on the contrary, if the local function uses the local function as the return value, the scope of the local function will be expanded, and it can be used inside the function. It can also be used in the scope of the function.

2. Function call

The basic syntax format of function call is as follows:

[Return value] = Function name ([Formal parameter value])

Among them, the function name refers to the name of the function to be called; the formal parameter value refers to the value of each formal parameter that is required to be passed in when the function is created. If the function has a return value, we can receive the value through a variable, or not. It should be noted that how many formal parameters there are to create a function, then how many values ​​need to be passed in when calling, and the order must be the same as when creating a function. Even if the function has no parameters, the parentheses after the function name cannot be omitted.

 

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113565023