抽象
创建函数
>>> def hello(name):
return 'hello,'+name+'!'
>>> hello('qiaochao')
'hello,qiaochao!'
函数注释
1)以#开头
2)直接写上字符串
函数定义可以嵌套
>>> def foo():
def bar():
print 'hello aaa '
bar()
>>> foo()
hello aaa
函数递归调用:
>>> def jiecheng(n):
if n == 1 :
return 1
else:
return n*jiecheng(n-1)
>>> jiecheng(10)
3628800
二元查找:
def search(sequence,number,lower,upper):
if lower == upper :
assert number == sequence[upper]
return upper
else :
middle = (lower + upper) // 2
if(number > sequence[middle]):
return search(sequence,number,middle+1,upper)
else:
return search(sequence,number,lower,middle)
print search([1,2,3,4,5,6,7,8,9,10],7,0,9)
6
----------------------------------------------------------------
>>> def hello(greeting,name):
print '%s , %s!' % (greeting,name)
>>> hello(greeting='hello',name='qiaoc')
hello , qiaoc!
注意:这里可以指定参数传值,这样就不会担心值对应的参数对不对 --- 关键字参数
>>> def hello(greeting='hi ',name='qiaochao'):
print '%s , %s!' % (greeting,name)
>>> hello()
hi , qiaochao!
注意:定义函数可以让参数有默认值
------------------------------------------------------------------
收集参数
>>> def print_params(title,*params):
print title
print params
>>> print_params('Params:',1,2,2)
Params:
(1, 2, 2)
>>> print_params('ass :')
ass :
()
注意:*的意思是收集参数,如果不提供任何供收集的元素,params就是个空元组
>>> def print_params_1(**params): -----** 字典参数
print params
>>> print_params_1(x=1,y=2,c=3)
{'y': 2, 'x': 1, 'c': 3}
>>> def print_params_2(x,y,z=3,*params,**keybar):
print x,y,z
print params
print keybar
>>> print_params_2(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_2(1,2)
1 2 3
()
{}
反转过程
>>> def add(x,y):
return x+y
>>> params=(1,2)
>>> add(*params)
3
** --- 也适用于字典参数
-----------------------------------------------------------------------
全局变量 ---- global 定义
>>> x=1
>>> def change_global():
global x
x=x+1
>>> x
1
>>> change_global()
>>> x
2
---------------------------------------------------------------------------