首頁  >  文章  >  後端開發  >  python中函數的詳細說明

python中函數的詳細說明

高洛峰
高洛峰原創
2017-03-08 10:17:071582瀏覽

斐波拉希數列

>>> 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<stop:
        result.append(i)
        i+=step
    return result

>>> print story(job=&#39;king&#39;,name=&#39;Gumby&#39;)
Once upon a time,there was aking called Gumby.
>>> print story(name=&#39;Sir Robin&#39;,job=&#39;brave knight&#39;)
Once upon a time,there was abrave knight called Sir Robin.
>>> params={&#39;job&#39;:&#39;language&#39;,&#39;name&#39;:&#39;Python&#39;}
>>> print story(**params)
Once upon a time,there was alanguage called Python.
>>> del params[&#39;job&#39;]
>>> print story(job=&#39;store of genius&#39;,**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,&#39;Helld,world&#39;)
Received redundant parameters: (&#39;Helld,world&#39;,)
>>> 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)
<function multiplyByFactor at 0x0000000002F8C6D8>
>>> 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))
[&#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;]
>>> 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,[&#39;ASDF&#39;,&#39;jskk&#39;])
[&#39;Asdf&#39;, &#39;Jskk&#39;]

## filter函數

它接收一個函數和一個列表(list),這個函數依次對每個元素進行判斷,返回True或False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新列表

>>> def is_not_empty(s):
    return s and len(s.strip())>0

>>> filter(is_not_empty,[None,&#39;dshk&#39;,&#39;  &#39;,&#39;sd&#39;])
[&#39;dshk&#39;, &#39;sd&#39;]
>>> 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 &#39;Begin&#39;

>>> lambda:&#39;begin&#39;
<function <lambda> at 0x0000000002ECC2E8>
>>> s=lambda:&#39;begin&#39;
>>> 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(),[&#39;8ui&#39;,&#39;&j&#39;,&#39;lhg&#39;,&#39;)j&#39;])
[&#39;8ui&#39;, &#39;lhg&#39;]
#########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中文網! ###
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn