python3函数定义

(1)函数的定义

def test(x):
    "The function definitions"
    x += 1
    return x
print(test(5))

#def:定义函数的关键字
#test:函数名
#():定义形参
#"..."描述函数功能
#x += 1:代码块
#return:返回值

    

(2)位置参数

注:赋的值必须和形参一一对应,不能多也不能少。

def cal(x,y,z):
    print(x)
    print(y)
    print(z)
    return x
cal(2,5,6)

(3)关键字参数

注:赋的值可以调换顺序,数量也是不能多且不能少。

def cal(x,y,z):
    print(x)
    print(y)
    print(z)
    return x
cal(z = 6, x = 2, y = 5)

(4)位置参数和关键字参数同时存在

注:位置参数必须在关键字参数左边。

def cal(x,y,z):
    print(x)
    print(y)
    print(z)
    return x
cal(2, z = 6, y = 5)

(5)已经定义了值的参数

def handle(x,type='mysql'):
    print(x)
    print(type)
handle('hello')
返回值:
hello
mysql



handle('hello',type='sqlite')
返回值:
hello
sqlite



handle('hello','sqlite')
返回值:
hello
sqlite

(6)参数组

注:*args数组,**kwargs字典。

def test(x,*args):
    print(x)
    print(arg)
test(1,2,3,4,5,6)
返回值:
1
(2, 3, 4, 5, 6)



def test(x,*args):
    print(x)
    print(arg)
test(1,*['th','handsome',666])
返回值:('th', 'handsome', 666)



def test(x,**kwargs):
    print(x)
    print(kwargs)
test(1,**{'name':'th'})
返回值:
1
{'name': 'th'}

猜你喜欢

转载自blog.csdn.net/maergaiyun/article/details/82313677