函數最初被設計出來,是用來減輕重複 coding 一段相同的代碼,這之間只有代碼 (方法,Method) 的重用,但還沒有物件導向OO整個Object 的屬性與方法被封裝重用的概念。

函數的定義很簡單,使用 def 這保留字,而其宣告方式如下:

def 函數名(參數名) :

例如:

>>> def print_count(): # 函數宣告
...    print('Good')
...    print('Morning')
...    print('Mr.')
...
>>> print_count()  # 函數調用
Good
Morning
Mr.

函數允許巢狀 Nested 結構,即一個函數的主體 Body 可以呼叫 call 另一個函數, 例如:

>>> def repeat_count(k):
...    for i in range(1,k):
...      print_count()
...
>>> repeat_count(2)
Good
Morning
Mr.

對函數 repeat_count(k) 而言,k 是形參 (parameter),而調用此函數 repeat_count(2) 的 2 是實參(argument)。

在函數的Body內定義的變數 Variable 都是局部的 Local,即它們只有存在函數內,例如:

>>> m = 6
>>> def repeat_count(k):
...    for i in range(1,k):
...       print_count()
...    m = 3
...
>>> repeat_count(2)
Good
Morning
Mr.
>>> print(m)
6

這範例我們宣告一個全局 Global 變數 m,並且指定 Assign 其值為 6,但在函數repeat_count(k) 同樣宣告一個同名的變數 m,指定其值為 3。,當呼叫調用此函數後,m 的值顯示依然為 6。

函數在被呼叫計算後,可以定義返回值 Return Value (Fruitful Function)。例如:

>>> def repeat_count(k):
...    for i in range(1,k):
...       print_count()
...    return ('OK')
...
>>> status = repeat_count(2)
Good
Morning
Mr.
>>> print(status)
OK

函數 repeat_count(2) 被呼叫後,將其返回值 'OK' 指定給變數 status。

還有一種函數,自己呼叫自己,此類函數被稱為遞歸(Recursive)函數。例如:

>>> def factorial(n):
...    if n == 1:
...       return 1
...    else:
...       return n * factorial(n - 1)
...
>>> factorial(3)
6
>>> factorial(4)
24
>>> factorial(5)
120

有關遞歸函數的概念較複雜,需另闢章節說明。

/end

05-11 22:23