First, the function
1. What is a function
function (functio), the word derives from mathematics, but the concept of "function" in programming is very different from the function in mathematics and can be understood as a set of encodings that implement a particular function. Functions in programming also have many different names in different languages. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.
Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.
2. Features of functions
- Reduce duplicate code
- To make the program extensible
- Make programs easier to maintain
3. Definition and invocation of functions
You can define a function that you want to function, and here are the simple rules:
- The function code block begins with a def keyword followed by the function identifier name and parentheses ().
- Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
- The first line of the function statement can optionally use the document string-for storing the function description.
- The function contents begin with a colon and are indented.
- Return[expression] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
def functionname (parameters): "Function _ Document String" function_suite return [expression]
Defines a function that gives the function a name, specifies the parameters contained in the function, and the code block structure.
function calls directly with the function name plus arguments: "functionname (Parameters)"
4. function return value (returns)
To get the result of the function execution, you can return the result using the return statement
Attention:
- 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
Python Basics-Functions