python---函數

來源:互聯網
上載者:User

標籤:必須   數組   高階函數   函數的參數   一個   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---函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.