1 Fibonacci 斐波那契序列 & callable() & __doc__ & help()
#note:如果使用raw_input,则返回的是plain string,需要进行int转换
def fib():
num = input('how many numbers you want to get? ')
fibs = [0,1]
for i in range(num-2):
fibs.append(fibs[-2]+fibs[-1])
return fibs
print fib()
x = 1
print callable(x) #False
print callable(fib) #True 3.0 print hasattr(fib,__call__)
def fdocstring(self):
'this is a example for documenting function - docstring'
pass
print fdocstring.__doc__
help(fib)
print fib.__doc__
2没有return或者return没有数据,的函数,实际返回为None
# return nothing (default None)
def notReal():
print 'return nothing'
return
print 'not show'
print '1----------'
notReal() # return nothing
print '2----------'
print notReal() # return nothing None
3参数
传入值若是seq,dict等object,则传入为地址,可以对实参进行修改
s = [1,2,3]
def f1(string):
s [0] = 10
string.append(4)
f1(s)
print s
4example p145
5指定参数名称,调用函数 & 一次传多个参数 * **
def f2(p1,p2):
print p1,p2
f2(p2='2',p1='1') #1 2
def muti1(*i):
print i
muti1(1) #(1,)
muti1(1,2,3)#(1, 2, 3)
def muti2(*i,**j): #cannot have two **j, **j dict
print i
print j
muti2(1,2,3,name='lili',no=2)
(1,2,3)
{'name':'lili','no':2}
def add(x,y): return x+y
p = (1,2)
print add(*p) #3
def with_stars(**p):
print '---', p['name'],p['no']
p = {'name':'lili','no':1}
with_stars(**p) # --- lili 1
6 vars(),返回dictionary
x = 1
scope = vars()
print scope[‘x’] #1
7 global(),全局变量
x = 100
def change():
x = 50
y = 60
print 'change() x = ',x
print 'change() global()[x]',globals()['x'] # 100,show global one
global y #chang to global,can show outside of this func
y = y+100
change()
print y
8 NESTED SCOPES,嵌套调用
def out(i):
def inter(j):
def inter1(k):
print('----1')
return i*j*k
print('----2')
return inter1
print('----3')
return inter
print out(2)(4)(3) # ---- 3 2 1 24
9 递归
# -- Factorial
def factorial(n):
result = n
for i in range(1,n):
result *= i
return result
print factorial(1)
def factorial1(n):
if n==1:
return 1
else:
return n*factorial1(n-1)
print factorial1(2)
# -- power
def power(x,n):
if n == 0:
return 1
result = 1
for i in range(n): #range(3)1,2,3;range(1,3)1,2
result *=x
return result
print '---',power(2,3)
def power1(x,n):
if n==0:
return 1
else:
return x*power(x,n-1)
print power1(2,3)
example p161
11 Functional programming
# -- map
# pass all the elements of a sequence through a given function
print map(str,range(10))
value={'01':'lili','02':'lucy'}
value1=[1,2,3]
print map(str,value) #['02', '01']
print map(str,value1) #['1', '2', '3']
# -- filter
# to filter out items based on a Boolean function
def func(x):
if x >=0: return True
if x<0 : return False
seq=[-1,0,2,3,-2]
print filter(func,seq) #seq make func return ture;
# -- lambda
# for define simple function,primarily used with map/filter and reduce
print filter(lambda x:x>=0,seq)
# -- reduce
num = [1,2,3,4]
num1 = [1]
print reduce(lambda x,y:x+y,num)
print reduce(lambda x,y:x+y,num1)