斐波拉希数列
>>> fibs
[0, 1]>>> n=input(‘how many fibonacci numbers do your what?’)
how many fibonacci numbers do your what?10
>>> for n in range(n-2):
fibs.append(fibs[-2]+fibs[-1])
>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
注意:内建的callable函数可以用来判断函数是否可以调用
def 定义函数
>>> def hello(name):
print “hello”+name
>>> hello(‘world’)
helloworld
用函数写斐波拉希数列
>>> def fibs(num):
s=[0,1]
for i in range(num-2):
s.append(s[-2]+s[-1])
>>> fibs(10)
注意:return语句从函数中返回值
函数说明:如果给函数写文档,让其他人能理解的话,可以加入注释(#开头)。另外一种方法就是直接写上字符串。
>>> def square(x):
‘calculates the square of the number x.’
return x*x
>>> square.__doc__
‘calculates the square of the number x.’
内建的help函数,可以得到关于函数,包括它的文档字符串信息
>>> help(square)
help on function square in module __main__:
square(x)
calculates the square of the number x.
在函数内为参数赋予新值不会改变外部变量的值:
>>> def try_to_change(n):
n=’mr,gumby’
>>> name=’mrs,entity’
>>> try_to_change(name)
>>> name
‘mrs,entity’
字符串(以及数字和元组)是不可改变的,即无法修改。若将可改变的数据结构(列表或字典)修改,参数会被修改
>>> n=[‘bob’,’alen’]
>>> def change(m):
m[0]=’sandy’
>>> change(n[:])
>>> n
[‘bob’, ‘alen’]
>>> change(n)
>>> n
[‘sandy’, ‘alen’]
关键字参数和默认值
>>> def hello(name,greeting=’hello’,punctuation=’!’):
print ‘%s,%s%s’ % (greeting,name,punctuation)
>>> hello(name=’nsds’)
hello,nsds!
>>> hello(name=’nsds’,greeting=’hi’)
hi,nsds!
收集参数
返回元组:
>>> def print_params(*params):
print params
>>> print_params(‘testing’) #返回元组
(‘testing’,)
>>> print_params(1,2,3)
(1, 2, 3)
>>> def print_params_2(title,*params):
print title
print params
>>> print_params_2(‘params:’,1,2,3)
params:
(1, 2, 3)
返回字典
>>> def print_params_3(**params):
print params
>>> print_params_3(x=1,y=2,z=3)
{‘y’: 2, ‘x’: 1, ‘z’: 3}
>>> def print_params_4(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar
>>> print_params_4(1,2,3,5,6,7,foo=1,bar=2)
2 3
(5, 6, 7)
{‘foo’: 1, ‘bar’: 2}
>>> print_params_4(1,2)
2 3
()
{}
调用元组、字典
>>> def add(x,y):return x+y
>>> params=(1,2)
>>> add(*params)
>>> def with_stars(**kwds):
print kwds[‘name’],’is’,kwds[‘age’],’years old’]
>>> def without_starts(kwds):
print kwds[‘name’],’is’,kwds[‘age’],’years old’
>>> args={‘name’:’nsds’,’age’:24}
>>> with_stars(**args)
nsds is 24 years old
>>> without_starts(args)
nsds is 24 years old
>>> add(2,args[‘age’])
星号只在定义函数(允许使用不定数目的参数)或者调用(”分割”字典或者序列)时才有用
>>> def foo(x,y,z,m=0,n=0):
print x,y,z,m,n
>>> def call_foo(*args,**kwds):
print “calling foo!”
foo(*args,**kwds)
>>> d=(1,3,4)
>>> f={‘m’:’hi’,’n’:’hello’}
>>> foo(*d,**f)
3 4 hi hello
>>> call_foo(*d,**f)
calling foo!
3 4 hi hello
几个例子
>>> def story(**kwds):
return ‘once upon a time,there was a’ \
‘%(job)s called %(name)s.’ % kwds
>>> def power(x,y,*others):
if others:
print ‘received redundant parameters:’,others
return pow(x,y)
>>> def interval(start,stop=none,step=1):
if stop is none:
start,stop=0,start #start=0,stop=start
result=[]
i=start
while i>> print story(job=’king’,name=’gumby’)
once upon a time,there was aking called gumby.
>>> print story(name=’sir robin’,job=’brave knight’)
once upon a time,there was abrave knight called sir robin.
>>> params={‘job’:’language’,’name’:’python’}
>>> print story(**params)
once upon a time,there was alanguage called python.
>>> del params[‘job’]
>>> print story(job=’store of genius’,**params)
once upon a time,there was astore of genius called python.
>>> power(2,3)
>>> power(y=3,x=2)
>>> params=(5,)*2
>>> power(*params)
>>> power(3,3,’helld,world’)
received redundant parameters: (‘helld,world’,)
>>> interval(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> interval(1,5)
[1, 2, 3, 4]
>>> power(*interval(3,7))
received redundant parameters: (5, 6)
修改全局变量
>>> def f():
global x
x=x+1
>>> f()
>>> x
>>> f()
>>> x
嵌套
>>> def multiplier(factor):
def multiplybyfactor(number):
return number*factor
return multiplybyfactor
>>> double=multiplier(2)
>>> double(5)
>>> multiplier(2*5)
>>> multiplier(2)(5)
递归(调用)
阶乘和幂
>>> def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
>>> factorial(5)
>>> range(3)
[0, 1, 2]
>>> def power(x,n):
result=1
for i in range(n):
result *= x
return result
>>> power(5,3)
>>> def power(x,n):
if n==0:
return 1
else:
return x*power(x,n-1)
>>> power(2,3)
二元查找
>>> def search(s,n,min=0,max=0):
if max==0:
max=len(s)-1
if min==max:
assert n==s[max]
return max
else:
middle=(min+max)/2
if n>s[middle]:
return search(s,n,middle+1,max)
else:
return search(s,n,min,middle)
>>> search(seq,100)
map函数
它接收一个函数和一个列表,并通过函数依次作用在list的每个元素上,得到一个新的list并返回
>>> map(str,range(10))
[‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’]
>>> def f(x):
return x*x
>>> print map(f,[1,2,3,4,5,6,7])
[1, 4, 9, 16, 25, 36, 49]
>>> def format_name(s):
s1=s[0].upper()+s[1:].lower()
return s1
>>> print map(format_name,[‘asdf’,’jskk’])
[‘asdf’, ‘jskk’]
filter函数
它接收一个函数和一个列表(list),这个函数依次对每个元素进行判断,返回 true或 false,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新列表
>>> def is_not_empty(s):
return s and len(s.strip())>0
>>> filter(is_not_empty,[none,’dshk’,’ ‘,’sd’])
[‘dshk’, ‘sd’]
>>> def pfg(x):
s=math.sqrt(x)
if s%1==0:
return x
>>> import math
>>> pfg(100)
>>> pfg(5)
>>> filter(pfg,range(100))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> def is_sqr(x):
return math.sqrt(x)%1==0
>>> is_sqr(100)
true
>>> filter(is_sqr,range(100))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
lambda函数
也叫匿名函数,即,函数没有具体的名称,而用def创建的方法是有名称的
>>> def foo():return ‘begin’
>>> lambda:’begin’
>>> s=lambda:’begin’
>>> print s()
begin
>>> s= lambda x,y:x+y
>>> print s(1,2)
>>> def sum(x,y=6):return x+y
>>> sum2=lambda x,y=6:x+y
>>> sum2(4)
>>> filter(lambda x:x*x,range(1,5))
[1, 2, 3, 4]>>> map(lambda x:x*x,range(1,5))
[1, 4, 9, 16]>>> filter(lambda x:x.isalnum(),[‘8ui’,’&j’,’lhg’,’)j’])
[‘8ui’, ‘lhg’]
reduce函数
它接收一个函数和一个列表(list),函数必须接收两个参数,这个函数依次对列表每个元素进行调用,返回结果值组成的新列表
>>> reduce(lambda x,y:x*y,range(1,5))
24
>>> reduce(lambda x,y:x+y,[23,9,5,6],100) #初始值为100,依次相加列表中的值
143
更多python中函数的详细说明相关文章请关注php中文网!