def function_name(arg1 = default1, arg2 = default2):
pass
return something下例中 hello() 函數需要一個參數 name ,已經先提供一個預設值 "John"
def hello(name = "John"):
print("Hello, ", name, "!")
hello("Mary")
hello()
hello("9527")
hello("Tony")
hello()
hello("Sherry")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def11.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

下例中 hello() 函數需要三個參數 name ,有兩個已經提供一個預設值
def hello(age, name = "John", day = "Monday"):
print("Hello, ", name, "!")
print("Today is", day)
print("You are", age, "years old.")
hello(12, "Mary", "Sunday")
hello("Bill")
hello("9527", "Wednesday")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def12.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

"9527" 原本是要給 name 的,可是 name 卻變成 "Wednesday" ,而 age 是 "9527" 。這是因為呼叫 (call) 函數時,參數必須按照順序提供,若沒有按照順序,就需要把參數名稱打出來,同時沒有給預設值的參數必須給值。例如
def hello(age, name = "John", day = "Monday"):
print("Hello, ", name, "!")
print("Today is", day)
print("You are", age, "years old.")
hello(name = "Mary", day = "Sunday", age = 12)
hello(name = "Bill", age = 33)
hello(day = "Wednesday", age = 23, name = "9527")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def12.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

| 中英文術語對照 | |
|---|---|
| 函數 | function |
| 參數 | parameter |
| 預設值 | default argument |
| 參數列 | paramenter list |
| 數值 | value |
| 呼叫 | call |
參考資料
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
1 則留言:
Good Job! It really helps. Thanks.
張貼留言