My inspiration from reading *C++ Primer*, *Effective C++*, *More Effective C++*, *The C++ Standard Library* and some experience from coding.
Include:
* Debug
* C++ Syntax
* Habit && Optimization
* Trick
* Trap
* Reference
2. 函式:將部份程式碼集結一起完成某功能
語法
範例:階乘函式
121
def fn( arg1 , arg2 , ... ) : # fn:函式名稱 arg1, arg2 ... :參數
body # 函式內執行區塊
def factorial( n ) :
"""計算 n 階乘"""
p = 1
for i in range(2,n+1) : p *= i
return p
函式說明:
緊接在函式名稱之後,以三個雙(單)引號夾住的字串(可跨列)用來當成函式的
說明文字,可使用「函式名稱.__doc__」取得字串,即 factorial.__doc__
回傳資料:
使用 return arg 回傳 arg 值後離開函式,可有多個 return 式子,
若無 return 則回傳 None
若有重複定義相同名稱的函式,程式執行最後定義的函式
國立中央大學數學系
3. 函式參數設定 (一):位置對應
參數位置對應:依參數次序一一對應
參數使用方式:
122
def power( a = 10 , n = 1 ) :
p = 1
for i in range(n) : p *= a
return p
函式呼叫參數設定 運算結果 說明
power(3,2) 9 a = 3 , n = 2
power(3) 3 a = 3 , n = 1(預設值)
power() 10 a = 10(預設值) , n = 1(預設值)
國立中央大學數學系
4. 函式參數設定 (二)
預設值的設定順序由末尾往前設定
123
# 錯誤:末尾的 n 沒有設定預設值
def power( a = 10 , n ) :
....
# 正確:預設值由參數列末尾位置往前設定
def power( a , n = 1 ) :
....
國立中央大學數學系
6. 函式要在使用前定義
串列元素 n 次方:無回傳(等同回傳 None)
串列元素 n 次方:有回傳
125
# 更動串列參數數值
def powers( foo , n = 1 ) : # (1)需先定義函式
for i in range(len(foo)) :
foo[i] = foo[i]**n
return
a = [2,3]
powers(a,4) # (2)才能使用
print(a) # 輸出 [16, 18]
# 沒有變更串列參數數值
def powers( foo , n = 1 ) : # 先定義函式
return [ c**n for c in foo ]
a = [2,3]
b = powers(a) # a = [2,3] b = [2,3]
c = powers(a,3) # a = [2,3] c = [8,27]
國立中央大學數學系
7. 大型程式的開發方式:倒裝寫法
將程式主要執行步驟寫於檔案前端 main 函式內,其餘函式撰寫於後,
最後在檔案末尾執行 main 函式。例如:
126
def main() : # (1) 定義主函式 main()
while True : # (2) 程式步驟寫在主函式內
n = int( input("> ") )
for i in range(1,n+1) :
a = list(range(0,i))
for x in powers(a,2) :
print( x , end=" " )
print()
# 產生 foo 串列元素的 n 次方串列
def powers( foo , n = 1 ) : # (3) 其餘函式定義於主函式之後
return [ c**n for c in foo ]
main() # (4) 最後執行主函式
輸出:
> 3 > 4
1 1
1 4 1 4
1 4 9 1 4 9
1 4 9 16
國立中央大學數學系