函數(Python)

來源:互聯網
上載者:User

標籤:splay   col   固定   tle   div   http   通過   記憶體   代碼   

函數是什嗎?

  電腦的函數,是一個固定的一個程式段,或稱其為一個子程式,它在可以實現固定運算功能的同時,還帶有一個入口和一個出口,所謂的入口,就是函數所帶的各個參數,我們可以通過這個入口,把函數的參數值代入子程式,供電腦處理;所謂出口,就是指函數的函數值,在電腦求得之後,由此口帶回給調用它的程式。

使用函數的特性:減少代碼重複,程式可擴充,容易維護。

文法定義:

 1 # @Software: PyCharm 2 def say():#定義函數 3     print(‘hello world‘) 4  5 say()#調用函數 say 6  7  8  9 hello world10 11 Process finished with exit code 0
View Code

 

# @Software: PyCharma,b = 5,2def calc (x,y):    res = x**y    return  resc = calc(a,b)print(c)25Process finished with exit code 0

函數的參數:

形參:變數只有在被調用的時候才被分配記憶體單元,調用結束即釋放記憶體單元,也就是只有在函數內部有效。

實參:必須有確定的值,將值傳遞給形參。

# @Software: PyCharma,b = 5,2#a,b 實參def calc (x,y):#x,y 為形參    res = x**y    return  resc = calc(a,b)#實參傳遞給形參print(c)25Process finished with exit code 0
View Code

位置參數:調用函數時根據函數定義的參數位置來傳遞參數。

def students(name,age,sex,num):#name age sex num 為位置參數    print(‘下面是學生資訊‘)    print(‘名字:‘,name)    print(‘年齡:‘,age)    print(‘性別‘,sex)    print(‘學號:‘,num)students(‘jack‘,22,‘boy‘,150313)students(‘siri‘,5,‘girl‘,180254)下面是學生資訊名字: jack年齡: 22性別 boy學號: 150313下面是學生資訊名字: siri年齡: 5性別 girl學號: 180254Process finished with exit code 0

預設參數:預設參數指的是當函數調用中省略了實參時自動使用的一個值。例如,如果將void wow(int n)設定成n有預設值為1,則函數調用wow()相當於wow(1)。這極大地提高了使用函數的靈活性。

def students(name,age,sex,num,addr=‘0370‘):#addr為預設參數    print(‘下面是學生資訊‘)    print(‘名字:‘,name)    print(‘年齡:‘,age)    print(‘性別‘,sex)    print(‘學號:‘,num)    print(‘學會‘,addr)    students(‘jack‘,22,‘boy‘,150313)students(‘siri‘,5,‘girl‘,180254)下面是學生資訊名字: jack年齡: 22性別 boy學號: 150313地址 0370下面是學生資訊名字: siri年齡: 5性別 girl學號: 180254地址 0370Process finished with exit code 0

 非固定參數:在定義時不確定需要傳入多少參數。

# @File    : jia.pydef students(name,age,*args):#*args 將多餘的值放入一個元組中    print(name,age,args)students(‘jack‘,22)students(‘siri‘,1,‘girl‘,‘read‘)D:\untitled\venv\Scripts\python.exe D:/untitled/bogls/jia.pyjack 22 ()siri 1 (‘girl‘, ‘read‘)Process finished with exit code 0

 

# @File    : jia.pydef students(name,age,*args,**kwargs):#**kwargs 將多餘的值放入字典中    print(name,age,args,kwargs)students(‘jack‘,22)students(‘siri‘,1,‘girl‘,‘read‘,sex=‘girl‘,addr=‘0370‘)jack 22 () {}siri 1 (‘girl‘, ‘read‘) {‘sex‘: ‘girl‘, ‘addr‘: ‘0370‘}Process finished with exit code 0

 

函數(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.