def function_name():
passpass 為關鍵字之一,其為甚麼事情都不做的陳述 (statement) 。
函數內容的部份須縮排 (indentation) ,縮排的區塊 (block) 專屬於函數,如下定義的 fun() 函數,印出遞增的數字
def fun():
i = 0
while i < 6:
print(i)
i += 1
fun()
fun()
fun()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cf13.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

fun() 函數從 0 逐行遞增 1 印到 5 ,底下沒有縮排的地方一共呼叫 (call) fun() 三次,因此一連印出 18 個數字。
i 為 fun() 函數內的區域變數 (local variable) , fun() 之外的地方無法存取 i 的值,例如
def fun():
i = 0
while i < 6:
print(i)
i += 1
fun()
print(i)
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def02.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 會發生如下的執行錯誤

這是因為直譯器 (interpreter) 在 fun() 函數的區塊內才認得變數 i ,離開函數的地方,直譯器便不認識這個名稱。
模組 (module) 也就是 .py 檔案中定義函數,需注意先有函數定義,才可進行函數呼叫。如將上例函數定義與呼叫的順需顛倒,如下
fun()
fun()
fun()
def fun():
i = 0
while i < 6:
print(i)
i += 1
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def03.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 會發生如下的執行錯誤

因為 Python 直譯器從頭一行一行的解譯程式原始碼 (source code) , fun() 既非 Python 的內建名稱,也還沒解譯到底下定義的部份,因此直譯器直接發生 NameError ,終止程式的進行。
| 中英文術語對照 | |
|---|---|
| 函數 | function |
| 物件 | object |
| 關鍵字 | keyword |
| 識別字 | identifier |
| 陳述 | statement |
| 縮排 | indentation |
| 區塊 | block |
| 呼叫 | call |
| 區域變數 | local variable |
| 直譯器 | interpreter |
| 模組 | module |
| 原始碼 | source code |
參考資料
http://docs.python.org/py3k/tutorial/controlflow.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/tutorial/controlflow.html
http://docs.python.org/py3k/reference/compound_stmts.html
沒有留言:
張貼留言