1. Function basics
Functions are the basic program structure provided by Python for maximum code reuse and minimization of code redundancy.
A function is a design tool that enables programmers to break down complex systems into manageable parts.
Functions are used to package related functions and parameters.
There are 4 types of functions that can be created in Python:
Global functions: Defined in the module
Local functions: nesting in other functions
Lambda function: An expression
Method: A function that is associated with a specific data type and can only be used with a data type association
Python provides a number of built-in functions.
Note: There are two ways to view Python's built-in functions.
1, https://docs.python.org/3/library/functions.html
2. Interactive mode: Help (__BUILTINS__)
2. Create a function
Grammar:
def functionname (parameters):
Suite
Some of the relevant concepts:
DEF is an executable statement. You can therefore appear anywhere you can use a statement, or even nested in other statements, such as if or while.
Def creates an object and assigns it to a variable name (that is, the function name).
Return is used to return the result object, which is optional; a function without a Retrun statement automatically returns the None object. When multiple values are returned, they are separated by commas and a combination returns an object as a tuple.
After the DEF statement is run, you can call it in the program by appending parentheses after the function.
2.1. Document parameters
If you want to write a document to a function so that other people with the function can understand it, you can add comments (starting with #). Another way is to write the string directly. Such strings can be useful elsewhere, such as after a DEF statement (and at the beginning of a module or class). If you write a string at the beginning of a function, it is stored as part of the function, which is called a document string.
Example:
def Square (x): ' Calculates the square of the number x. ' Return x*x
The document string can be accessed as follows:
square.__doc__
Note: __doc__ is a function property. The double underscore in the property indicates that it is a special property.
2.2. Parameter passing: The parameter is passed by automatically assigning the object to the local variable.
Immutable parameters are passed through "value":
Changing the value of a parameter inside a function simply makes it reference another object.
mutable parameters are passed through the pointer:
Changing the value of a formal parameter inside a function modifies the referenced object directly.
There are two ways to avoid variable parameters being modified by functions:
Directly passing a copy of a mutable object: TestFunc (a,b[:])
Create a copy of a mutable parameter inside a function: b=b[:]
example: variable parameter:>>> l1 = [1,2,3]>>> def f1 (x): .... X.pop () ... print ( x) ... >>> F1 (L1) #这里我们发现当调用函数f1时, the value of the list L1 is modified. It's them. They are all pointing to the same reference. [1, 2]>>> l1[1, 2] immutable:>>> l1 = [1,2,3]>>> def f1 (x): ... x.pop () ... print (x) ... #注意我们这里调 The method of using Parameters l1[:] is equivalent to making a full copy of the list L1, so they do not point to the same reference. >>> F1 (l1[:]) [1, 2]>>> l1[1, 2, 3]
2.3, function parameter model
By default, parameters are passed through their positions, from left to right, which means that you must precisely pass as many parameters as the function head parameter. However, this mechanism can also be changed by keyword parameters, default parameters, or parameter containers.
Positional parameters: left-to-right
keyword argument: When calling a function, the syntax of "Name=value" is used to match the
default parameter by the parameter name: The syntax of "Name=value" is used to directly give the variable a value when defining the function, thus passing in a value that can be less than the number of arguments br> def f1 (x,y,z=9)
Variable parameter: A parameter that starts with * when defining a function, which can be used to collect any number of arguments based on a location or keyword
def f1 (*x): Identifies the collected results as tuples to identify
Def F1 (**x): The collected results are used as dictionaries to identify the
variable parameter unpacking: When calling a function, use the arguments that begin with * to scatter the parameter collection, passing any number of arguments based on the location or keyword
Note: When you call a function, if you mix positional and keyword parameters, On the left, write all the positional parameters, and then write all the keyword parameters. When you define a function with a parameter that has a default value: The parameter is left and the argument with the default value is placed to the right.
Use variadic requirements when calling functions:
to define functions using *: Collect positional parameters
Define functions using * *: Collect keyword Parameters
Example: variable parameters for collecting positional parameters, returning results to tuples >>> def F10 (*x): ... Print (x) ... >>> m = 3>>> n = 5>>> o = 9>>> F10 (m) (3,) >>> F10 (M,o) (3, 9) >&G The t;> variable parameter, used to collect the keyword parameters, returns the result as a dictionary. >>> def F11 (**x): ... Print (x) ... >>> F11 (x=1,y=5,z=9) {' Z ': 9, ' x ': 1, ' Y ': 5} variable parameter unpacking: must match >>> l1 = ["Sun", "Mon", "Tus"]> >> x, y, z = l1>>> print (x, y, z) Sun Mon Tus example:>>> l1 = ["Sun", "Mon", "Tus"]>>> def f1 (x, y, z) :... Print (x, y, z) ... >>> F1 (*l1) Sun Mon Tus
2.4. Function Scope:
Python creates, alters, or looks up variable names in a namespace.
The position in the code where the variable name is assigned determines the scope to which it can be accessed.
The function defines the local scope, and the modules define the global scope.
Each module is a global scope, so the scope of the global scope is limited to a single program file.
Each call to a function creates a new local scope, and the assigned variable is local if it is declared as a global variable using global.
All variable names can be summarized as local, global, or built-in (provided by the __builtins__ module).
Function Variable scope: LEGB principle
The smaller the scope, the more priority.
Python's Path to Growth "third": Functions