Python定義函數

1.1 定義函數基礎

# define the function

def fib(n):

    # print the Fibonacci series up to n.

    a, b = 0, 1;

    while  a < n :

        print a;

        a, b = b, a +b;

 

1.2 函數默認參數

''' 

    default arguments

'''

def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please') :

    while True:

        ok = raw_input(prompt);

        if ok in ['y', 'Y', 'yes'] :

            return True;

        if ok in ['n', 'no', 'nop'] :

            return False;

        retries = retries - 1;

        if retries < 0:

            raise IOError('refusenik user');

        print complaint;

 

1.3 不定參數

'''

    Arbitrary arguments function

'''

def arbitraryArgsFunc(arg1, *args):

    # just print the arbitrary arguments

    for i in range(0, len(args)):

        print(args[i]);

arbitraryArgsFunc('arg1', 'arg2', 'arg3');

 

1.4 Lambda表達式

'''

    lamba function, just like the function  template

'''

def make_incrementor(n):

    return lambda x:x + n;

f = make_incrementor(42);

print(f(0));


值得注意的是當要使函數接收元組或字典形式的參數的時候,有一種特殊的方法,它分別使用*和**前綴。這種方法在函數需要獲取可變數量的參數的時候特別有用。

def powersum(power, *args): 
     '''Return the sum of each argument raised to specified power.''' 
      total = 0 
     for i in args: 
                total += pow(i, power) 
        return total
由於在args變量前有*前綴,所有多餘的函數參數都會作爲一個元組存儲在args中。如果使用的是**前綴,多餘的參數則會被認爲是一個字典的鍵/值對。

發佈了45 篇原創文章 · 獲贊 22 · 訪問量 49萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章