Blog 10

1. Definition Function

def 函数名(等同于变量名)():
    '''对函数的描述信息'''
    code
  • Characteristics defined functions: a function definition process, only detect syntax, the code is not performed. When you call the function, it executes the code

2. Define the functions of three ways

  • Empty function

    def hanshu():
        pass
  • No-argument function

    def hanshu():
        x = 10
        y = 10
        print(x>y) #函数中有代码块
  • There are function parameters

    def hanshu(x,y):
        print(x>y) #函数中有代码块

3. calling function

Call a function is to use the function

def hanshu():
    x = 10
    y = 10
    print(x>y) #函数中有代码块
hanshu()   #函数名加()   调用函数
print(hanshu)   #直接打印函数名 :打印结果为函数的内存地址

4. return value of the function

Once you have defined the function, call the function return value there. The return value of the function defaults to None

We use return to return the function's return value. The return value can be any data type

def hanshu(x):
    x = x+10
    return x
y = hanshu(1)
print(y+10) # 打印结果为 21

return characteristics:

  • return is a return value, if there is no return value, default return None
  • return terminates the function, the following code will not run return, assuming there are multiple return, ran to meet the conditions of return would not run when other return
  • return can return multiple values, return values ​​received in the form of a tuple

The function parameters

1. The parameter (argument for receiving, descriptive sense)

Defining a function is generated, the function name in parentheses.

(1) position parameter (and no difference parameter)

Receiving from left to right argument

(2) Default parameter (parameter has a default value is the default parameter)

  • When the value is not passed to the default parameter values, the default value, if the value passed to it, it is passed in use

  • The default parameter behind only on the position of the parameter

2. arguments (formal parameters used to pass values, can be of any data type)

In parentheses when calling a function function name

(1) the position of arguments (argument and no difference)

From left to right to pass parameter values, parameter number, the number of arguments must

(2) Keyword argument (that is, and the definition of variables, the variable name is a parameter name)

  • According to the parameter name to a value
  • Keyword argument parameter must be placed in the rear position

3. The variable length parameter (unlimited length)

下面的可变长形参中   *   后面是一个类似变量名的东西,可以随便写

(1) variable length parameter

def hanshu(*lis): #  *lis  把所有传过来的所有实参按元组的形式存储, 如果 *lis 的前面存在其他形参,那么 *lis 接收的就是剩下的实参
    a,b,c,d,*_ = lis  # 以解压缩的方法取出想要的值
    print(a,b,c,d)

(2) variable length argument

def hanshu(*lis):
    print(max(lis))
lt = [1,2,3,4,5,6]
res = hanshu(*lt)  #   * 相当于解压缩,也就是把lt内的元素一个一个取出来传给形参

Guess you like

Origin www.cnblogs.com/Mcoming/p/11549891.html