在前面我們已經見過一些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.