http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net
分类: Python/Ruby
2011-09-30 15:22:10
注意:函数callable在Python3.0中不再可用,需要使用表达式hasattr(func,__call__)代替
++++++++++++++++++++++++++++++++++
6.2 记录函数1 文档字符串
6.3 收集参数
>>> def print_params(*params):
print params
>>> print_params("hello")
('hello',)
>>> print_params("hello",'world')
('hello', 'world')
星号的意思是“收集其余的位置参数”,如果不提供任何供收集的元素,params就是个空元组:
>>> print_params()
+++++++++++++++++++++++++++++++++++++++
处理关键字参数的函数参数:
>>> def print_params(**params):
print params
>>> print_params(x=1,y=2)
{'y': 2, 'x': 1}
6.4 反转过程
+++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++
练习
6.5 作用域
变量和所对应的值用的是个“不可见”的字典,实际上这么说已经很接近真实情况了,内建的vars函数可以返回这个字典:
警告:一般来说,vars返回的字典是不能修改的,因为根据官方的 Python文档的说法,结果是未定义的。
++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++
在函数内部将值赋给一个变量,它会自动为局部变量------除非告知Python将其声明为全局变量,方法是使用变量前调用语句:global 变量名
++++++++++++++++++++++++++++++++++++++++++++++++++++
6.6递归一个二分搜索算法
def search(sequence,number,lower=0,upper=None):
if upper is None:upper=len(sequence)-1
if lower==upper:
if number != sequence[upper]:
return -1
return upper
else:
mid=(lower+upper)//2
if number > sequence[middle]:
return search(sequence,number,middle+1,upper)
else:
return search(sequence,number,lower,middle)
seq=[34,67,8,123,4,100,95]
seq.sort()
print seq