# 讲解python参数和作用域的使用

def fibs(num):
result = [0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result

def square(x):
'计算x的平方'
return x*x

#文档字符串可以按如下方式访问：
>>> square._doc_
'计算x的平方'

2.1 我能改变参数吗
在函数内为参数赋予新值，不会改变外部任何变量的值：

>>> def to_change(n):
n = 's'
>>> name = 'b'
>>> to_change(name)
>>> name
'b'

>>> def change(n):
n[0] = 'ss'
>>> names = ['aa','zz']
>>> change(names)
>>> names
['ss', 'zz']

2.2 关键字参数和默认值

>>> def hello(greeting,name):
print '%s,%name!'
>>> hello(greeting = 'hello',name = 'world')
hello,world!

>>> def hello(greeting = 'hello',name = 'world'):
print '%s,%name!'

>>> hello()
'hello,world!'
>>> hello('greeting')
'greeting,world!'
>>> hello(name = 'universe')
'hello,universe!'

2.3 收集参数

>>> def print_para(*paras):
print paras
>>> print_para('ss')
('ss',)
>>> print_para(1,2,3)
(1, 2, 3)

>>> def print_params(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar

>>> print_params(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params(1,2)
1 2 3
()
{}

2.4 反转过程

return x+y
>>> params =(1,2)
3

（2）在定义的时候使用

>>> def with_stars(**kds):
print kds['name'],'is',kds['age'],'years old'
>>> args = {'name':'Mr.Gumby','age':42}
>>> with_stars(**args)
Mr.Gumby is 42 years old

>>> x=1
>>> scope = vars()
>>> scope['x']
1
>>> scope['x'] += 1
>>> x
2

（1）当函数直接返回值时有基本实例（最小可能性问题）
（2）递归实例，包括一个或者多个问题最小部分的递归调用。

A.阶乘
>>> def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
[/code]
B.幂

>>> def power(x,n):
if n == 0:
return 1
else:
return x * power(x,n-1)

C.二元查找（假设number必然在序列sequence中）

>>> def search(sequence,number,lower,upper):
if lower == upper:
assert num == 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)

Top