標籤:必須 數組 高階函數 函數的參數 一個 turn lob class 過程
函數特性:減少重複代碼,使程式變的可擴充,使程式變得易維護
1.定義函數
#定義函數def func1(): """test""" print("this is test") return 0#定義過程 #通俗的說過程就是沒有返回的函數,但python會返回一個nonedef func2(): """test1""" print("this is test") #調用函數x = func1()y = func2()#列印函數傳回值print(x,y)#0 None
2、函數傳回值
#函數傳回值作用:判斷該函數執行情況。def test1(): print("this is test") #返回nonedef test2(): print("this is test") return 0 #返回0def test3(): print("this is test") return 1,"hello",["a","b"],{"a":"b"} #返回一個元組x = test1()y = test2()z = test3()print(x)print(y)print(z)
3、函數參數
#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}
4、局部變數與全域變數
name1 = "fengxiaoli" #全域變數,對所有函數生效,如果全域變數定義的是字串或者數字,則在局部修改之後只對局部生效,def test(): #對全域還是沒生效,如果全域變數定義的是字典,列表,集合,類,則在局部修改之後對全域也生效 #global name #在函數中聲明全域變數,慎用 name1 = "cx" #局部變數,只在該函數中生效 print(name1)test()print(name1)# 輸出:# cx# fengxiaoliname2 = ["cx","fengxiaoli"]def test2(): name2[0] = "CX" print(name2)test2()print(name2)# 輸出:# ['CX', 'fengxiaoli']# ['CX', 'fengxiaoli']
5、遞迴函式
#遞迴特性:必須有一個明確的結束條件。每次進入更深層次的遞迴,問題規模相比上次遞迴都應有所減少。遞迴效率不高def calc(n): print(n) if int(n/2)>0: return (calc(int(n/2)))calc(10)
6、高階函數
#變數可以指向函數,函數的參數能接收變數,那麼一個函數就可以接收另一個函數作為參數,這種函數稱為高階函數def test(a,b,f): res = f(a)+f(b) print(res)test(-5,3,abs) #這裡的abs是一個求絕對值的函數
7、匿名函數
calc = lambda x:x*3print(calc(3))
python---函數