Python3--function
- Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.
- Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.
Define a function
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, and the parentheses can be used to define the 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] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
def function name (argument list): function Body
Instance
# a function that asks for two number and def Add (x, y): return x + y# call function print(Add (10, 10))
anonymous functions
Python uses lambda to create anonymous functions.
Anonymity means that a function is no longer defined in a standard form such as a DEF statement.
- Lambda is just an expression, and the function body is much simpler than def.
- The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
- The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
- Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.
Lambda [Arg1 [, Arg2,..... argn]]:expression
Instance
Lambda x, y:x+yprint(Add (10,10))
2018-04-14-python