函数定义
在python中函数的定义以及调用如下代码所示:
def test(x):
y = x+1
return yresult = test(2)
print(result)
多个返回值的情况
如果在函数中return多个值,会将那多个值打包成一个元组传出,如下代码所示
def test(x):
y1 = x+1
y2 = x+2
return y1,y2result = test(2)
print(result) #打印结果为(3, 4)
使用关键字参数的情况
使用关键字参数,则传参的位置可以不固定,但是个数还是要相匹配,此外在调用的时候关键字参数一定要在普通参数的右边,如下代码所示
def test(x,y,z):
res = x - y - z
return resresult = test(y=1,x=5,z=2)
print(result) #打印结果为2
使用默认参数的情况
使用默认参数,传参的个数可以不匹配,如果默认参数的位置没有传,则使用默认值,这个是在定义的时候定义的,定义默认参数要写在最右边,如下代码所示
def test(name,sex = "man"):
print(name)
print(sex)test("CodeScrew")
#打印结果为CodeScrew man
test("CodeScrew","women")
#打印结果为CodeScrew women
使用参数组的情况
参数组中指的是可以传任意参数,一般**对应字典,*对应列表,如下代码所示
- 传入列表
def test(name,*args):
print(name)
print(args)test("CodeScrew",*[1,2,3,4])
#打印结果为CodeScrew (1, 2, 3, 4)
- 传入字典
def test(name,**kwargs):
print(name)
print(kwargs)test("CodeScrew",x=1,y=2)
#打印结果为CodeScrew {'x': 1, 'y': 2}
test("CodeScrew",**{"x":1,"y":2})
#打印结果为CodeScrew {'x': 1, 'y': 2}
def test(x,y,z):
res = x - y - z
return resresult = test(y=,x=,z=)
print(result) #打印结果为2