In Python, a function is defined by the keyword def, and its basic structure is as follows:
Define function name (parameter):
"""Document string" ""
state
Where function_name is the function name, parameters is the parameter list, a colon (:) indicates the beginning of the function body, and the statement in the function body is the code to be executed by the function.
2. Definition of function parameters
Functions in Python can accept zero or more parameters. These parameters are defined in the definition of the function and are used to provide the data input by the function. We can include the following types of parameters in the function definition:
-positional parameters: parameters passed in positional order, such as def foo(a, b);
-keyword parameter: the parameter passed by the parameter name, such as def foo(a= 1, b = 2);
-Default parameter: a parameter with a default value, which can be omitted when calling a function. Such as def foo(a= 1, b=2):
-Variable parameters: any number of parameters can be passed, such as def foo(*args):
-Keyword variable parameters: any number of keyword parameters can be passed, such as deffoo (* * kwargs);
3. Definition of function return value
This function can return a result to the caller, which is specified by the return statement. If the function has no return statement, it returns nothing by default. If the function has a return value, you should specify the return type in the function definition.
4. Function document string
In Python, the function document string is the first statement of a function. Usually, this is a multi-line string that describes the function and usage. It starts and ends with three quotation marks, as follows:
Define function name (parameter):
"""This is a document string." ""
state
5. Functional scope
In Python, the range of variables is determined by the position of the function definition. If variables are defined outside functions, they can be accessed throughout the program. If a variable is defined inside a function, it can only be accessed in that function. In addition, Python also supports nested functions and closures. In this case, internal functions can access the variables of external functions.