1.1 定义函数基础
# define the function
def fib(n):
1.2 函数默认参数
'''
'''
def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please') :
1.3 不定参数
'''
'''
def arbitraryArgsFunc(arg1, *args):
arbitraryArgsFunc('arg1', 'arg2', 'arg3');
1.4 Lambda表达式
'''
'''
def make_incrementor(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中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。