Basic function of python

function

Which function consists of four parts

  1. Declaring functions section def
  2. Function name: must begin with a letter or an underscore already has practical significance
  3. Parentheses (): parameter may be increased
  4. Code block: as long as the function is not running, the python is the result of the implementation will not control function within the code is correct, as long as the service syntax to

The function block having the characteristics

As long as the function is not running, the python is the result of the implementation will not control function within the code is correct, as long as the service syntax to

Three ways defined functions

# 1. 无参函数
def info():
    code...
    
# 2. 有参函数
def info(x,y)
    code...
    
# 3. 空函数
def info():
    pass

The return value of the function

def info(x,y):
    pass
    return 1
 
'''
    总结:
        1. return,可以返回任意数据类型的数据
        2. 但return返回任意数据类型的数据
        3. 默认返回None
        4. return有结束函数的作用,相当于break

'''

Functions functional description information

def self_max(*a,**b):
    '''
    函数的文档说明:
    :param a: 
    :param b: 
    :return: 
    '''
    print(a)
    print(b)

print(self_max.__doc__) # 查看函数的文档说明:

Function is divided into two phases

Definition Phase

# 定义
def info():
    pass

Call phases:

# 调用
info()

Katachisan

When you define a function, named parameters. Parameter descriptive sense, similar to the variable name, not the specific data type

Arguments

Call the function stage, passing parameters, known as arguments. Argument must be some specific data type

Positional parameters (position parameter, the position arguments)

# 位置参数

def info(a,b,c,x=50,y=30):  # a,b,c叫位置形参
    print(a,b,c,x,y)
    
info(1,2,3)     # 1,2,3叫位置实参

'''
1,2,3,50,30

'''




'''
    总结
        1. 两个参数的顺序必须一一对应,且少了一个参数都不可以。
        2. 位置参数必须要在关键字参数(形参和实参)的前面,不然解释器会报错。

'''

The default parameters

# 默认参数
def info(x=50,y=30):    # x,y叫默认参数
    print(x,y)

#调用
info()

'''
50 30
'''



'''
    总结:
        1. 函数调用时,若有实参传入,实参会覆盖默认值;否则使用默认参数
'''

Keyword argument

# 默认参数
def info(x=50,y=30):    # x,y叫默认参数
    print(x,y)

#调用
info(y=100,x=200)

'''
200 100

'''

'''
    总结:
        1. 关键字实参 利于 找到与形参的对应关系,并赋值给形参

'''

The variable length parameter / variable length argument

def self_max(*a,**b):       # 可变长形参 
    print(a)
    print(b)

num1_list = [1,2,3,4,5,6,7,8]
num2_dict = {"x":500,"y":200}

self_max(*num1_list,**num2_dict)    # 可变长实参


'''
(1, 2, 3, 4, 5, 6, 7, 8)
{'x': 500, 'y': 200}

'''




'''
    总结:
        1. *a 接受所有位置参数,然后以元组的形式保存下来
        2. **b 接受所有关键字实参,然后以字典的形式保存下来。
    
'''

Guess you like

Origin www.cnblogs.com/plf-Jack/p/10945684.html