函數特性:減小重複代碼,使程序變的可擴展,使程序變得易維護
1.定義函數
#定義函數 def func1(): """test""" print("this is test") return 0 #定義過程 #通俗的說過程就是沒有返回的函數,但python會返回一個none def func2(): """test1""" print("this is test") #調用函數 x = func1() y = func2() #打印函數返回值 print(x,y) #0 None
二、函數返回值python
#函數返回值做用:判斷該函數執行狀況。其餘程序有可能須要根據該返回值進行不一樣的操做 def test1(): print("this is test") #返回none def test2(): print("this is test") return 0 #返回0 def test3(): print("this is test") return 1,"hello",["a","b"],{"a":"b"} #返回一個元組 x = test1() y = test2() z = test3() print(x) print(y) print(z)
三、函數參數數組
#1.位置參數和關鍵字參數 def test1(x,y,z): print(x) print(y) print(z) test1(1,2,3) #位置參數,與順序有關 test1(y=2,z=3,x=1) #關鍵字參數,與位置無關 test1(1,z=3,y=2) #既有位置參數,又有關鍵字參數,位置參數不能再關鍵字參數前面 #2.默認參數 def test2(x,y=2): print(x) print(y) test2(1) #若是不指定y,則使用默認值,指定新值則用新值 test2(1,3) test2(1,y=3) #3.參數組 def test3(*args): #將傳入值轉化成一個元組 print(args) test3(1,2,3,4,5) test3(*[1,2,3,4,5]) #輸出 # (1, 2, 3, 4, 5) # (1, 2, 3, 4, 5) def test4(x,*args): print(x) print(args) test4(1,2,3,4,5) #輸出 # 1 # (2, 3, 4, 5) def test5(**kwargs): #將「關鍵字參數」轉化成一個字典 print(kwargs) test5(y=1,x=2,z=3) #輸出 # {'y': 1, 'x': 2, 'z': 3} def test6(name,age=18,**kwargs): print(name) print(age) print(kwargs) test6("feng",y=1,x=2) #輸出 # feng # 18 # {'y': 1, 'x': 2} test6("feng",23,y=1,x=2) #輸出 # feng # 23 # {'x': 2, 'y': 1}
四、局部變量與全局變量ide
name1 = "fengxiaoli" #全局變量,對全部函數生效,若是全局變量定義的是字符串或者數字,則在局部修改以後只對局部生效,\ def test(): #對全局仍是沒生效,若是全局變量定義的是字典,列表,集合,類,則在局部修改以後對全局也生效 #global name #在函數中聲明全局變量,慎用 name1 = "cx" #局部變量,只在該函數中生效 print(name1) test() print(name1) # 輸出: # cx # fengxiaoli name2 = ["cx","fengxiaoli"] def test2(): name2[0] = "CX" print(name2) test2() print(name2) # 輸出: # ['CX', 'fengxiaoli'] # ['CX', 'fengxiaoli']
五、遞歸函數函數
#遞歸特性:必須有一個明確的結束條件。每次進入更深層次的遞歸,問題規模相比上次遞歸都應有所減小。遞歸效率不高 def calc(n): print(n) if int(n/2)>0: return (calc(int(n/2))) calc(10)
六、高階函數this
#變量能夠指向函數,函數的參數能接收變量,那麼一個函數就能夠接收另外一個函數做爲參數,這種函數稱爲高階函數 def test(a,b,f): res = f(a)+f(b) print(res) test(-5,3,abs) #這裏的abs是一個求絕對值的函數
七、匿名函數spa
calc = lambda x:x*3 print(calc(3))