函式



我們認識了 print()input()int()str()、... 等函式,這些是 Python 本身提供給我們使用的,稱為「內建函式」。

 
abs()            delattr()      hash()          memoryview()    set()
all()            dict()         help()          min()           setattr()
any()            dir()          hex()           next()          slice()
ascii()          divmod()       id()            object()        sorted()
bin()            enumerate()    input()         oct()           staticmethod()
bool()           eval()         int()           open()          str()
breakpoint()     exec()         isinstance()    ord()           sum()
bytearray()      filter()       issubclass()    pow()           super()
bytes()          float()        iter()          print()         tuple()
callable()       format()       len()           property()      type()
chr()            frozenset()    list()          range()         vars()
classmethod()    getattr()      locals()        repr()          zip()
compile()        globals()      map()           reversed()      __import__()
complex()        hasattr()      max()           round()	 
 



我們也可以將自己常會用到的指令組成「自定」函式,方便自己重複使用


函式的基本語法
 
# def 是英文的 define (定義) 的意思
def 函式名([參數1], [參數2], ...):
    "註解, 簡述函式的功能及用法"    # 不是必要, 但鼓勵這麼做, 提高函式的可讀性
    指令 1
    指令 2
    指令 3
    ...
    ...
    [return 回傳結果]    # 不是必要的, 函式也可以不回傳
 


例 1 最簡單的函式
 
def hello():
    "hello 函式練習"
    print('hello world')


# 主程式
hello()
 
當您執行這個程式,就只是很單純地在螢幕上顯示 hello world 而已,這個 hello 函式,沒有傳入參數,也沒有回傳資料給主程式。

當您以把滑鼠移至主程式的 hello(),也會顯示 hello() 的說明,如同我們想知道內建函式的用法時的操作



當您的函式寫的較複雜,程式碼較多時,您的註解說明也會變多變長,這時的註解建議如下的格式:
 
# 函式的多行註解說明,首尾各以 3 個雙引號包起來
# 第 1 行依舊是函式的簡述及用法
# 第 2 行空白, 做為分隔用
# 第 3 行開始, 應該是 一個 或 多個 段落, 說明函式的呼叫方法。
def hello():
    """hello 函式練習

    hello 函式詳細說明

    不傳入任何參數

    在螢幕顯示 hello world
    """
    print('hello world')





# 主程式
hello()
 


例 2 當沒有自定函式,要計算圓面積時
 
# 假設有 A, B, C 三個圓的直徑 a, b, c
a = 10
b = 20
c = 30

# 計算 A, B, C 的面積
# 半徑 * 半徑 * 3.14
areaA = (a/2) * (a/2) * 3.14
areaB = (b/2) * (b/2) * 3.14    # 每次要計算面積都要寫同樣的計算式
areaB = (b/2) * (b/2) * 3.14    # 每次要計算面積都要寫同樣的計算式

print('A 的面積為 '+str(areaA))
print('B 的面積為 '+str(areaB))
print('C 的面積為 '+str(areaC))
 
將圓面積的計算寫成自定函式
 
def Area(diameter):
    "由直徑計算出面積"
    radius = diameter / 2
    return (radius* radius * 3.14)    # 傳回面積



# 主程式

# 假設有 A, B, C 三個圓的直徑 a, b, c
a = 10
b = 20
c = 30
  
areaA = Area(a)    # 呼叫函式
areaB = Area(b)
areaB = Area(c)
    
print('A 的面積為 '+str(areaA))
print('B 的面積為 '+str(areaB))
print('C 的面積為 '+str(areaC))
 


例 3 您也可以給參數預設值
 
def Hello(name='無名氏'):
    """Hello(名字)

    當使用者在參數未傳入名字時, 預設值為 無名氏
    """

    print('Hello', name)




# 主程式
Hello()
print('\n')
Hello('John')
 
執行結果:
 
Hello 無名氏


Hello John
 


例 4 多個參數,參數有 名稱預設值
 
def Hello(name='無名氏', weather='晴', temp=20):
    """Hello(name, weather, temp)

    參數 name 名字, 字串, 預設值 '無名氏'
        weather 天氣, 字串, 預設值 '晴'
        temp 溫度, 數字, 預設值 20
    """
    
    print('Hello', name, '今天天氣', weather, '溫度', temp)





Hello()
print('\n')

Hello('John','陰',15)
print('\n')

# 您也可以只傳入部份參數
# 而且不依照順序
# 但是這樣您就需要寫明參數名稱
# 這是 Python 很獨特的風格
Hello(temp=30, name='Ann')
 
執行結果:
 
Hello 無名氏 今天天氣 晴 溫度 20


Hello John 今天天氣 陰 溫度 15


Hello Ann 今天天氣 晴 溫度 30
 






⇑ 目錄 ⇑