Python學習筆記(5):函數

來源:互聯網
上載者:User

在前面我們已經見過一些Python內建函數,比如len和rang。現在我們來看看自訂函數,函數是通過def關鍵字來定義,後面跟函數名稱和圓括弧,括弧內可以包含參數,該行以冒號結束,接下來是語句塊,即函數體。

1. 簡單的sayHello函數
def sayHello():    print("Hello world!")#調用函數sayHello()
2. 帶形參函數
def printMax(a, b):    if a > b:        print(a, "is maximum.")    else:        print(b, "is maximum.")printMax(3, 4)
3. 局部變數
def func(x):    print("x is ", x)    x = 2    print("Changed local x to ", x)x = 50func(x)print("x is still ", x)

運行結果為:

x is  50
Changed local x to  2
x is still  50

4. 預設參數值
def say(message, times = 1):    print(message * times)say("ha")say("ha", 2)

運行結果為:

ha

haha

5. 關鍵參數
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

6. return語句
def maximum(x, y):    if x > y:        return x    else:        return yprint(maximum(2, 3))
7. 文檔字串DocStrings

Python有一個奇妙的特性,就是文檔字串(DocStrings),它的主要作用就是協助你的程式文檔更加簡單易懂。

def printMax(x, y):    '''Prints the maximum of two numbers.    The two values must be integers.'''    x = int(x)    y = int(y)    if x > y:        print(x, "is maximum.")    else:        print(y, "is maximum.")printMax(3, 5)print(printMax.__doc__)help(printMax)

運行結果為:

5 is maximum.
Prints the maximum of two numbers.
    The two values must be integers.
Help on function printMax in module __main__:

printMax(x, y)
    Prints the maximum of two numbers.
    The two values must be integers.

相關文章

聯繫我們

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