函数
用def语句创建函数。
>>> def hello(name):
return 'Hello,' + name + '!'
>>> print hello('world')
Hello,world!
>>>
文档化函数
在函数的开头写下字符串,它还作为函数的一部分进行存储,这称为文档字符串。
>>> def square(x):
'Calculates the square of the numbers x.'
return x*x
#文档字符串可以按如下方式访问:
>>> square.__doc__
'Calculates the square of the numbers x.'
>>>
返回值
Python中的函数都有返回值。
return xxx #返回xxx,xxx可以是一个值也可以是一个元组
return #返回None
无return语句 #返回None
参数
Python函数从程序中接收参数并进行特定的运算。
形参和实参引用同一个对象
>>> def change(n): #形参和实参引用同一个对象,所以在函数中对参数进行操作实际上是在值本身上修改的
n[0] = 0
>>> numbers = [1,2,3,4]
>>> numbers
[1, 2, 3, 4]
>>> change(numbers)
>>> numbers
[0, 2, 3, 4]
>>>
位置参数
>>> def hello(greeting,name):
print '%s,%s!' % (greeting,name)
>>> hello('hello','world') #输出结果和参数位置的关系很重要
hello,world!
>>> hello('world','hello')
world,hello!
>>>
关键字参数和默认值
>>> def hello(greeting,name):
print '%s,%s!' % (greeting,name)
>>> hello(greeting='Hello',name='world') #输出结果和参数位置无关,这种使用参数名提供的参数叫做关键字参数
Hello,world!
>>> hello(name='world',greeting='Hello')
Hello,world!
>>>
关键字参数厉害之处在于可以为参数提供默认值。当为参数提供默认值时,调用函数时可以不传入参数,或者传入一部分参数,或传入所有参数。>>> def hello(greeting='Hello',name='world'):
print '%s,%s!' % (greeting,name)
>>> hello()
Hello,world!
>>> hello('Good')
Good,world!
>>> hello('Good','morning')
Good,morning!
>>> hello(name='Tom')
Hello,Tom!
>>>
收集参数
*:收集的位置参数转化为元组
**:收集的关键字参数转化为字典
>>> def print_params(*params):
print params
>>> print_params(1,2,3,4)
(1, 2, 3, 4)
>>>
>>> def print_params(**params):
print params
>>> print_params(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>>
收集参数的逆过程
>>> def add(x,y): #在定义函数时用星号可以允许多参数输入,用于收集参数;在调用函数时用星号“分割”字典或序列,是收集参数的逆过程
return x + y #星号只有在定义函数或者调用函数时才有用,定义和调用都使用星号是没意思的
>>> numbers = [1,2]
>>> add(*numbers)
3
作用域
全局变量
globals(),vars()返回全局变量的字典
局部变量
locals()返回局部变量的字典
在函数中声明全局变量
>>> x = 1
>>> def change_global():
global x #当全局变量别屏蔽时,可以使用global声明全局变量
x = x + 1
>>> change_global()
>>> x
2
>>>
递归
函数调用函数自身,逐步逼近基本实例。
>>> def fibs(n): #返回第n个斐波那契数
if n == 1:
return 0
elif n == 2:
return 1
else:
return fibs(n-1) + fibs(n-2)
函数式编程
Python在函数式编程方面有用的函数:map、filter和reduce函数
map函数:将序列中的元素全部传递给一个函数。
>>> map(str,range(10)) #相当于[str(i) for i in range(10)]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>
filter函数:可以基于一个返回布尔值的函数对元素进行过滤
>>> def func(x): #[x for x in seq if x.isalnum()]
return x.isalnum()
>>> seq = ['foo','x41','?!','***']
>>> filter(func,seq)
['foo', 'x41']
>>>
>>> numbers = [1,2,3,4,5,6,7,8,9]
>>> reduce(lambda x,y:x+y,numbers)
45
>>>
lambda表达式
>>> seq = ['foo','x41','?!','***']
>>> filter(lambda x: x.isalnum(),seq)
['foo', 'x41']
>>>