python---函數

來源:互聯網
上載者:User

標籤:固定   預設參數   過程   pre   imp   return   接收   數學   實參   

函數學習,要點總結如下:

1. 函數預設可以沒有傳回值,沒有傳回值則返回為None
2. 函數可以有多個傳回值,類型可以不同,但其實多個傳回值整體上是一個元組
3. 關鍵參數不能夠寫在位置參數前面
 1 # -*- coding:utf-8 -*- 2 # LC 3  4 import time 5 #函數: 6 def logger():               #定義日誌函數 7     time_format = ‘%Y-%m-%d  %X‘        #定義時間格式 8     time_current = time.strftime(time_format)       #抓取目前時間 9     with open("log_file","a") as f:10         f.write("%s this is end\n"%time_current)11 12 def func1():13     """to declare the function"""           #說明這個函數是做什麼的14     print("this is function1")              #函數工作模組,邏輯15     logger()16     return 0                                    #函數傳回值17 18 #過程:                #過程是沒有傳回值的函數,在python中,過程預設返回None19 def func2():20     """function 2"""21     print("this is function2")22     logger()23     return 1,{"name":"lvcheng","age":"18"}      #可返回多個值24 25 x = func1()             #調用函數26 y = func2()27 print(x)28 print(y)29 30 def func3(x,y,z):              #x,y為形參,同為位置參數31     print(x,y,z)32     return x,y,z33 34 func3(1,2,3)          #位置參數調用,位置需要與形參一一對應35 func3(1,2,z=3)36 func3(y=2,z=3,x=1)      #關鍵字調用,關鍵參數,與形參順序無關37 38 #預設參數39 def func4(x,y=3):        #y是預設參數40     print(x)41     print(y)42 func4(1)43 func4(1,5)44 #預設參數可以不傳遞,如果有傳遞,則是傳遞的值45 #用途 1,預設安裝的時候,2, 連結資料庫的連接埠號碼等46 47 #參數組,對於實參不固定函數的實現48 def func5(*args):       # *是關鍵字,元組的方式傳遞49     print(args)50 51 # *args接受N個位置參數,轉換成元組的方式52 53 test1 = func5(1,2,3,4,5)    # 1,2,3,4,5以(1,2,3,4,5)元組的方式傳遞給args54 test1 = func5(*[1,2,3,4])55 56 #參數組,以字典的方式實現57 58 def func6(**kwargs):59     print(kwargs)60     print(kwargs[‘name‘])       #取字典裡的值61     print(kwargs[‘age‘])62 # **kwargs接收N個關鍵字參數,轉換成字典的方式傳遞63 64 65 test2 = func6(name="lc",age=9)          #必須傳遞關鍵字參數66 test2 = func6(**{"name":"lc","age":10})67 68 69 def func7(name,age=19,**kwargs):        #有形參,有預設參數,有參數組70     print(name)71     print(age)72     print(kwargs)73 74 test3 = func7("lc",21,sex="M",hobby="girl")75 test3 = func7("lc",sex="M",hobby="girl",age = 32)76 77 def func8(name,age=19,*args,**kwargs):78     print(name)79     print(age)80     print(args)81     print(kwargs)82 83 func8("lc",2,3,4,sex="M",hobby="money")

 

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.