Python定义函数

来源:互联网 发布:按键精灵 js 插件 编辑:程序博客网 时间:2024/05/17 18:24

1.1 定义函数基础

参考:http://www.cnblogs.com/xuqiang/archive/2011/04/22/2025276.html

# 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中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。
0 0
原创粉丝点击