一、函数
def 函数名(参数): ... 函数体 ... 返回值
函数的定义主要有如下要点:
- def:表示函数的关键字
- 函数名:函数的名称,日后根据函数名调用函数
- 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
- 参数:为函数体提供数据
- 返回值:当函数执行完毕后,可以给调用者返回数据。
有参数实现
# def test(x):
# '''
# y=2*x+1
# :param x:整形数字
# :return: 返回计算结果
# '''
# y=2*x + 1
# return y
#
# a=test(3)
# print(a)
无参数实现
# def test():
# '''
# y=2*x+1
# :param x:整形数字
# :return: 返回计算结果
# '''
# x=3
# y=2*x + 1
# return y
#
# a=test()
# print(a)
函数的返回值
总结:
返回值数=0:返回None
返回值数=1:返回Object
返回值数>1:返回tuple
函数参数
# def test(x,y,z): #x=1,y=2,z=3
# print(x)
# print(y)
# print(z)
# 位置参数,必须一一对应,缺一不行,多一也不行
# test(1,2,3)
# 关键字参数,无须一一对应,缺一不行多一也不行
# test(y=1,x=3,z=2)
# 混合使用位置参数必须在关键字参数左边
# test(1,y=2,3) #报错
# test(1,3,y=2) #报错
# test(1,3,z=2)
# test(1,3,z=2,y=4) #报错,y 传入了多个值
默认参数:
# def handle(x,type='mysql'):
# print(x)
# print(type)
# handle('hello') #返回:hello mysql
# # handle('hello',type='sqlite') #返回:hello sqlite
# # handle('hello','sqlite')
动态参数:参数组:**字典 *列表
1)
# def test(x,*args):
# print(x)
# print(args)
# print(args[0][0])
# test(1)
# test(1,2,3,4,5,6)
# test(1,{'name':'alex'})
# test(1,['x','y','z']) #把列表当作一个整体传进去
# test(1,*['x','y','z']) #遍历列表
# test(1,*('x','y','z')) #遍历元祖
2)
# def test(x,**kwargs):
# print(x)
# print(kwargs)
# test(1,y=2,z=3)
# test(1,y=2,z=3,z=4) #会报错:一个参数不能传两个值,传值重复
3)
# def test(x,*args,**kwargs):
# print(x)
# print(args,args[-1])
# print(kwargs,kwargs.get('y'))
# # test(1,1,2,3,4,5,x=1,y=2,z=3) #报错
# # test(1,1,2,3,4,5,y=2,z=3)
# test(1,*[1,2,3],**{'y':1})