Function acquaintance
Function is a collection operation and gives it a name. You have used too many Python built-in functions, such as string.title () and list.sort () . We can also define your own functions, they can "teach" Python to make some new behavior
The definition of a function
- Use the keyword def tell Python that you will want to define a function.
- Give your function a name. Function name should be able to show that the function does.
- Function to the data needed from the name.
They are variable names, but only within the function.
These names are called function parameters ( arguments )
- Be sure to define the function ends in a colon.
- Inside the function, you want to write arbitrary code.
1. The role of function
- A large number of functions can reduce the duplication of code
- Function can improve the reusability
- The code is a function of the encapsulation layer
2. The basic structure of the function
def 函数名(参数):
函数体
3. calling function
Function name()
The role of the function name
- call function
- Receiving a return value of the function
- The return value back to the caller
- No matter what the position as long as the function name (), it is to call the function
4. return value of the function
return
- return: do not write return is to return None return to write did not write the value returned or None
- return: this function can be terminated, and the code is not performed below the return
- return: the object can be returned to any Python
- return: return a plurality of objects received in the form of a tuple
The function parameters
Parameter (hereinafter, arranged in the priority parameter)
Location parameter, the position of the dynamic parameter, default parameter values, the parameter Dynamic Keyword
Arguments
Position arguments, keyword arguments
Dynamic parameters:
Dynamic Location Parameters - * args, extra reception position parameter tuples displayed in the form of
dynamic keyword parameters - ** kwargs, redundant keywords received parameters displayed in the form dictionary
# 示例
# 位置传参
def d(a, b):
print(a, b)
d(2, 3)
# 关键字传参
def d(a, b):
print(a, b)
d(b=2, a=3)
# 混合传参
def d(a, b, c=10):
print(a, b, c)
d(2, 3)
# 动态参数
def func(*args,**kwargs):
print(args)
print(kwargs)
func(1,2,3,4,a = 1, b = 2)
# 综合
def func(a,b,c,*args,**kwargs):
print(a,b,c)
print(args)
print(kwargs)
func(1,2,3,4,cc = 1, bb = 2)
6. Use of a first object and function name
- Function name can be assigned as a value
- Function name can be used as an argument to another function
- Function name can be used as the return value of another function
- Function name can be used as container elements