Hi! 大家好,我是Eric,這次教大家Python的函式(function)!![]()
■ 使用函式。函式是有名稱的程式碼,括弧內是參數,參數可用名子指定,如下的sep:
print(1,2,3,sep="--")
■ 定義函式
def fibonacci(N, a = 0, b = 1): #a=0, b=1表示我們自己設定的預設參數值,若沒有輸入a,b,則預設分別為0,1
        L[]
        a,b= 0,1
        while len(L) < N:
          a, b = b, a + b
          L.append(a)
        return L
fibonacci(10)
def real_imag_conj(val)
       return val.real, val.imag, val.conjugate()
            
r, i, c = real_imag_conj(3 + 4j)
print(r, i, c)
■ 可變參數
def catch_all(*args, **kwargs):      # *表示將其展開為列表; **表示將其展開為字典
     print("args =", args)
     print("kwargs = ", kwargs) 
         
catch_all(1, 2, 3, a=4, b=5)   
catch_all('a', keyword=2)
■ 匿名(Lambda)函式
add = lambda x, y: x + y
add(1, 2)
def add(x, y):
   return x + y
data = [{'first':'Guido', 'last':'Van Rossum', 'YOB':1956},
        {'first':'Grace', 'last':'Hopper', 'YOB':1906},
        {'first':'Alan', 'last':'Turing', 'YOB':1912}]
orted(data, key=lambda item: item['first']    #根據名子排序
sorted(data, key=lambda item: item['YOB'])     #根據出生日期排序