C++猿的Python筆記03-函數

來源:互聯網
上載者:User
  基礎資料型別 (Elementary Data Type)  整型,長整型,浮點,複數,字串

 

  變數  

無需聲明或定義類型,在需要時賦值即可使用。 

 

  函數定義  

def 函數名(參數列表) 

變數使用無需聲明或定義類型,函數也因此沒有必要定義傳回型別。

預設情況下返回的是None。

 

   函數的注意點   

1. 形參是值傳遞

2. 為外部變數賦值,使用global關鍵字

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x    
x = 50
func(x)
print 'Value of x is', x

3. 支援預設參數

def say(message, times = 1):
    print message * times
say('Hello')
say('World', 5)

4. 支援關鍵參數。即指定實參的形參。

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)

輸出

>>> 
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
>>> 

5. pass表示空語句塊

def someFunction():
    pass

6. 文檔字串 DocStrings

在函數定義後的第一個邏輯行若是字串,則是這個函數的文檔字串。

即可被調用的說明語句。調用方法為 函數名.__doc__

文檔字串的慣例是:

一個多行字串,它的首行以大寫字母開始,句號結尾。

第二行是空行,

從第三行開始是詳細的描述。 

def printMax(x, y):
    '''This is DocStrings.
    
    return max number.'''
    x = int(x) # convert to integers, if possible
    y = int(y)
    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__


 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.