def test(x): ''' 2*x+1 :param x:整形数字 :return: 返回计算结果 ''' y=2*x+1 return y print(test(2))
输出 5
过程:就是没有返回值的函数
def test01(): msg = 'test01' print(msg) test01()
输出
test01
def test02(): msg = 'test02' print(msg) return 'sg' test02() print(test02())
输出
test02
test02
sg
def test03(): msg = 'test03' print(msg) return 1,2,3,4,'a',['alex'],{'name':'alex'},None print(test03())
输出
test03 (1, 2, 3, 4, 'a', ['alex'], {'name': 'alex'}, None)
def test04(): msg = 'test03' print(msg) return {'name':'alex'} print(test04())
输出
test03 {'name': 'alex'}
def test(x,y,z):#x=1,y=2,z=3 print(x) print(y) print(z) p=test(1,2,3) print(p) #位置参数,必须一一对应,缺一不行多一也不行
输出
1
2
3
None
def test(x,y,z):#x=1,y=2,z=3 print(x) print(y) print(z) test(y=1,x=3,z=4) #关键字参数,无须一一对应,缺一不行多一也不行
输出
3 1 4
def test(x,y,z):#x=1,y=2,z=3 print(x) print(y) print(z) #位置参数必须在关键字参数左边 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)#报错
def handle(x,type='mysql'): print(x) print(type) handle('hello') handle('hello',type='sqlite') handle('hello','sqlite')
hello
mysql
None
hello
sqlite
None
hello
sqlite
None
#参数组:**字典 *元组 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}
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) #报错 test(1,1,2,1,1,11,1,y=2,z=3)
输出
1 (1, 2, 1, 1, 11, 1) 1 {'y': 2, 'z': 3} 2