函數定義
在python中函數的定義以及調用如下代碼所示:
def test(x): y = x+1 return y result = test(2) print(result)
多個返回值的情況
如果在函數中return多個值,會將那多個值打包成一個元組傳出,如下代碼所示
def test(x): y1 = x+1 y2 = x+2 return y1,y2 result = test(2) print(result) #打印結果為(3, 4)
使用關鍵字參數的情況
使用關鍵字參數,則傳參的位置可以不固定,但是個數還是要相匹配,此外在調用的時候關鍵字參數一定要在普通參數的右邊,如下代碼所示
def test(x,y,z): res = x - y - z return res result = 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 res
result = test(y=1,x=5,z=2)
print(result) #打印結果為2