day9 函数
函數基本格式
1 def test(x): # x 為形參 2 """ 3 2*x+1 4 :param x:整型數字 5 :return: 返回 6 """ 7 y=2*x+1 # 運算過程 8 return y # 返回結果:返回值 9 print(test) 10 b = test(3) # 代入實參運行函數進行計算 11 print( b ) # 得到返回值并打印出來?
參數可以不帶的函數
1 def test():2 """3 2*x+14 :param x:整型數字5 :return: 返回6 """7 x = 38 y=2*x+19 return y 10 b = test() 11 print( test())
?形參,實參的對比
1 def calc(x,y): # 形參,只在函數內部有效,函數運算完就釋放掉了 2 res = x**y 3 return res 4 c = calc(a,b) # 實參,函數外的真正開辟了內存的參數 5 print(c)位置參數,一一對應,缺一不可 1 def test(x,y,z): 2 print(x) 3 print(y) 4 print(z) 5 test(1,2,3)
關鍵字參數,無需一一對應,缺一不可 1 def test(x,y,z): 2 print(x) 3 print(y) 4 print(z) 5 test(y=1,z=2,x=3)
位置參數必須在關鍵字參數左邊,參數不能空,可能來回賦值就亂了 1 def test(x,y,z): 2 print(x) 3 print(y) 4 print(z) 5 # test(1,z=2,3) # 報錯 6 # test(1,3,y=3) # 報錯
默認參數,定義初始參數,但是如果被賦值則取消默認參數 1 def handle(x,type=None): 2 print(x) 3 print(type) 4 handle("hello") 5 handle("hello",type="sqskl") 6 handle("hello","sqskl")
參數組: * 列表 ** 字典 1 def test (x,*args): 2 # 傳多個不曉得會多少或者以后做擴展的時候,用*args表示接受列表 3 # 或者**kwargs接受字典 4 print(x) 5 print(args) 6 print(args[3]) 7 test(1,2,3,4,5,6) 8 test(1,[1,2,3,4,5]) # 位置參數的形式傳參,不論你是什么列表字典都當做一個元素來傳 9 test(1,*[1,2,3,4,5]) # 若不想要他作為一個整體元素,列表加* ,字典加** ,可以將內容獨立做元素 10 test(1,y=2,z=3,z=6) #一個參數不能傳兩次 # 直接提示報錯標紅了 1 def test (x,*args,**kwargs): 2 # 兩者混用的時候,**kwargs必須放在最后面,不然會違背位置參數必須放在關鍵字參數左邊的原則 3 print(x) 4 print(args,args[-1]) 5 print(kwargs,kwargs["y"]) 6 test(1,11,111154546,123,y=3,z=4) 7 test(1,*[11,111154546,123],**{"y":3,"z":4}) 8 # 列表參數傳遞給*args用元祖方式進行傳遞 9 # 關鍵字參數傳遞給**kwargs 用字典的方式傳遞
?
轉載于:https://www.cnblogs.com/shijieli/p/9687042.html
總結
- 上一篇: 在EXCEL指定SHEET页,指定文字位
- 下一篇: Access denied for us