Chapter 11. [function] acquaintance

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

  1. A large number of functions can reduce the duplication of code
  2. Function can improve the reusability
  3. 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

  1. call function
  2. Receiving a return value of the function
  3. The return value back to the caller
  4. No matter what the position as long as the function name (), it is to call the function

4. return value of the function

return

  1. return: do not write return is to return None return to write did not write the value returned or None
  2. return: this function can be terminated, and the code is not performed below the return
  3. return: the object can be returned to any Python
  4. return: return a plurality of objects received in the form of a tuple

The function parameters

  1. Parameter (hereinafter, arranged in the priority parameter)

    Location parameter, the position of the dynamic parameter, default parameter values, the parameter Dynamic Keyword

  2. Arguments

    Position arguments, keyword arguments

  3. 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

  1. Function name can be assigned as a value
  2. Function name can be used as an argument to another function
  3. Function name can be used as the return value of another function
  4. Function name can be used as container elements

Guess you like

Origin www.cnblogs.com/tianming66/p/11756336.html