# 有带形参的def test(x): ''' 2*x+1 :param x:整形数字 :return: 返回计算结果 ''' y=2*x+1 return ya=test(5)print(a)
# 不带形参的def test(): ''' 2*x+1 :param x:整形数字 :return: 返回计算结果 ''' x=3 #x取固定值 y=2*x+1 return ya=test()print(a)
函数的返回值;
def test01(): msg = 'test01' print(msg)def test02(): msg = 'test02' print(msg) return msgdef test03(): msg = 'test03' print(msg) return 1,2,3,4,'a',['alex'],{ 'name':'alex'},Nonedef test04(): msg = 'test03' print(msg) return { 'name':'alex'}t1=test01()t2=test02()t3=test03()t4=test04()print("没有返回值,函数结果None:",t1)print("有返回值",t2)print("多种返回值当成一个元组输出:",t3)print("单个返回值显示它本身:",t4)
实例结果;
test01test02test03test03没有返回值,函数结果None: None有返回值 test02多种返回值当成一个元组输出: (1, 2, 3, 4, 'a', ['alex'], { 'name': 'alex'}, None)单个返回值显示它本身: { 'name': 'alex'}
形参和实参:
# 其中calc(x,y)的x,y表示形参def calc(x,y): res = x**y return res # return x #返回值是函数中实参的值 # return yres=calc(2,4)#x=2,y=3print(res)# 用a,b等于实际的值,表示实参a=10b=10res=calc(a,b)print(res)
结果:
1610000000000
位置参数和关键字参数的区别:
def test(x,y,z): print(x) print(y) print(z)#位置参数,必须一一对应,缺一不行多一也不行test(1,2,3)#x=1,y=2,z=3#关键字参数,无须一一对应,缺一不行多一也不行test(y=1,x=3,z=4)# test(1,y=2,3)#报错,位置参数要在关键字参数左边# test(1,3,y=2)#报错,关键字参数与位置参数不符合test(1,3,z=2)# test(1,3,z=2,y=4)#报错,关键字参数重复# test(z=2,1,3)#报错,关键字参数与位置参数不符合
结果
123314132
默认参数的函数
def handle(x,type='mysql'): print(x) print(type)handle('hello')#没有输入type的值默认type='mysql'handle('hello',type='sqlite')#新的type值覆盖原来的值handle('hello','sqlite') #按照顺序一一对应
结果
hellomysqlhellosqlitehellosqlite
参数组:**字典 *列表
def test(x,*args): print(x) print(args)test(1)test(1,2,3,4,5)test(1,{ 'name':'alex'})test(1,['x','y','z'])test(1,*['x','y','z'])test(1,*('x','y','z'))
结果
1()1(2, 3, 4, 5)1({ 'name': 'alex'},)1(['x', 'y', 'z'],)1('x', 'y', 'z')1('x', 'y', 'z')
def test(x,**kwargs): print(x) print(kwargs)test(1,y=2,z=3)# test(1,1,2,2,2,2,2,y=2,z=3)#报错,位置参数不够# test(1,y=2,z=3,z=3)#会报错 :一个参数不能传两个值
结果
1{ 'y': 2, 'z': 3}
使用*args,**kwargs可以传入任何类型
def test(x,*args,**kwargs): print(x) print(args,args[-1]) print(kwargs,kwargs.get('y'))# test(1,1,2,1,1,11,1,x=1,y=2,z=3) #报错,由于x=1和x重复传入test(1,1,2,1,1,11,1,y=2,z=3)test(1,*[1,2,3],**{ 'y':1})
结果
1(1, 2, 1, 1, 11, 1) 1{ 'y': 2, 'z': 3} 21(1, 2, 3) 3{ 'y': 1} 1