1.定義
def test():
x+=1
return x
好處:*減少代碼重用
*保持一致性和易維護性
*可擴展性
2.關於有無返回值
無:過程就是沒有返回值的函數
有:一個————返回本身
def test():
s=[5,4,32,556,22]
return s
print(test())
#打印結果 [5, 4, 32, 556, 22]
多個————返回元祖
def test():
l=[5,4,32,556,22]
s='fjy'
return l,s
print(test())
##打印結果 ([5, 4, 32, 556, 22], 'fjy')
3.參數
**形參只有調用時才會執行,遇到時只進行編譯。
一個函數碰到一個return就結束
1.位置參數必須一一對應,缺一不可
def test(x,y,z):
print(x)
print(y)
print(z)
test(1,2,3)
2.關鍵字參數,無須一一對應,缺一不行多一也不行
def test(x,y,z):
print(x)
print(y)
print(z)
test(y=1,x=3,z=4)
3.混合使用,位置參數必須在關鍵字參數左邊
test(1,y=2,3)#報錯
test(1,3,y=2)#報錯
test(1,3,z=2)
******一個參數不能傳兩個值
test(1,3,z=2,y=4)#報錯
4.參數組:**字典 --關鍵字參數
*元祖 --可變參數
(*遍歷的意思,打印多個參數轉換為元祖)
def test(x,*args):
print(x)
print(args)
test(1) #打印結果:1
test(1,2,3,4,5) #打印結果: 1 (2, 3, 4, 5)
test(1,{'name':'alex'}) #打印結果: 1 ({'name': 'alex'},)
test(1,['x','y','z']) #打印結果: 1 (['x', 'y', 'z'],)
test(1,*['x','y','z']) #打印結果: 1 ('x', 'y', 'z')
test(1,*('x','y','z')) #打印結果: 1 ('x', 'y', 'z')
def test(x,**kwargs):
print(x)
print(kwargs)
test(1,y=2,z=3) #打印結果:1 {'y': 2, 'z': 3}
test(1,**{'y':5,'z':3}) #結果: 1 {'y': 5, 'z': 3}
**在這里key只能是字符類型