Python函數及其參數

來源:互聯網
上載者:User

標籤:other   most   還需   lin   bbb   ret   line   收集   mod   

定義函數def

>>> def MyfirstFunction():

print('第一個函數')

>>> MyfirstFunction()

第一個函數


函數的參數

>>> def MySecondFunction(name):

print(name + 'IloveYou')

>>> MySecondFunction('wc')

wcIloveYou


>>> def add(num1,num2):

return (num1 + num2)


>>> add(1,2)

3


形參和實參

形式參數(parameter)

實際參數(argument)


>>> def MySecondFunction(name):    函數定義過程中的name叫形參

print(name + 'IloveYou')

>>> MySecondFunction('tingting')    傳遞進來的tingting叫做實參,因為他是具體的參數值

tingtingIloveYou


函數文檔

>>> def MySecondFunction(name):

'測試測試'

print(name + 'IloveYou')

'測試函數文檔'


>>> MySecondFunction.__doc__

'測試測試'


函數關鍵字

>>> def saysome(name, word):

print(name + '改變' + word)

>>> saysome('世界','tingting')

世界改變tingting

>>> saysome(word='世界',name='tingting')

tingting改變世界


預設參數

>>> def saysome(name='我', word='世界'):

print(name + '改變' + word)

>>> saysome()

我改變世界

>>> saysome('蒼老師','教育')

蒼老師改變教育


收集參數(可變參數)

>>> def test(*params):

print('參數的長度是:',len(params));

print('第二個參數是:',params[1])

>>> test(2,'aaa','測試測試',3.1415)

參數的長度是: 4

第二個參數是: aaa


>>> def test2(*num,other):        收集參數後還需要有其他參數,那需要把其他參數定義為預設參數

print('第一個參數為:',num)

print('第二個參數為:',other)


>>> test2(1,2,'aaa',5,90,54)

Traceback (most recent call last):

  File "<pyshell#5>", line 1, in <module>

    test2(1,2,'aaa',5,90,54)

TypeError: test2() missing 1 required keyword-only argument: 'other'

>>> test2(1,2,'aaa',5,90,54,other = 'bbbb')

第一個參數為: (1, 2, 'aaa', 5, 90, 54)

第二個參數為: bbbb






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.