python之路-10-函數

來源:互聯網
上載者:User

標籤:第一個   字典   rgs   導致   類型   擴充   實現   font   write   

10.1函數定義及文法

定義: 函數是指將一組語句的集合通過一個名字(函數名)封裝起來,要想執行這個函數,只需調用其函數名即可

特性:1.減少重複代碼 2.使程式變的可擴充 3.使程式變得易維護

文法定義:

def sayhi():       #函數名

    print("Hello, I‘m nobody!")

sayhi()             #調用函數

樣本1:

#!Author:lanhan
#定義函數
def func1():
    ‘‘‘testing1‘‘‘
    print(‘in the func1‘)
    return 0

#定義過程(沒有傳回值的函數,沒有return)
def func2():
    ‘‘‘testingn2‘‘‘
    print(‘in the func2‘)
#函數調用
x=func1()
y=func2()
print(‘from func1 return is %s‘ %x)
print(‘from func2 return is %s‘ %y)

 

樣本2:

#!Author:lanhan
import time
def logger ():
    time_format = ‘%Y-%m-%d %X‘
    time_current = time.strftime(time_format)
    print(time.strftime(time_format))
    with open(‘a.txt‘,‘a+‘) as f:
        f.write(‘%s end action\n‘ %time_current)
def test1():
    print(‘in the test1‘)
    logger()
def test2():
    print(‘in the test2‘)
    logger()
def test2():
    print(‘in the test2‘)
    logger()
def test3():
    print(‘in the test3‘)
    logger()
test1()
test2()
test3()

 

10.2 傳回值

要想擷取函數的執行結果,就可以用return語句把結果返回

註:1.函數在執行過程中只要遇到return語句,就會停止執行並返回結果,so 也可以理解為 return 語句代表著函數的結束

  1. 如果未在函數中指定return,那這個函數的傳回值為None 
  2. 可以返回任意的集合、字典、元組的一切值

樣本1:

#!Author:lanhan
def test1():
    print(‘in the test1‘)

def test2():
    print(‘in the test2‘)
    return 0
def test3():
    print(‘in the test3‘)
    return 1,‘hello‘,[‘alex‘,‘lanhan‘],{‘name‘:‘lanhan‘}
x=test1()
y=test2()
z=test3()
print(x)
print(y)
print(z)

 

 

 

10.3 參數

10.3.1形參與實參

形參:變數只有在被調用時才分配記憶體單元,在調用結束時,即刻釋放所分配的記憶體單元。因此,形參只在函數內部有效。函數調用結束返回主調用函數後則不能再使用該形參變數

實參:可以是常量、變數、運算式、函數等,無論實參是何種類型的量,在進行函數調用時,它們都必須有確定的值,以便把這些值傳送給形參。因此應預先用賦值,輸入等辦法使參數獲得確定值

10.3.2 位置參數與關鍵字參數

位置參數:給函數傳參數要按順序

關鍵字參數:不想按順序就可以用關鍵參數,只需指定參數名

樣本1:

#!Author:lanhan
def test(x,y):
    print(x)
    print(y)
test(1,2)  #位置參數調用(與形參一一對應,實參數需與形參對應,不能多也不能少)
test(y=2,x=1) #關鍵字調用(與形參順序無關)
#位置參數和關鍵字參數混合使用,按照位置參數來傳值
#test(x=2,3)   #錯誤(關鍵參數必須寫在位置參數之後,第一個參數是位置參數第二個參數不能是第一個參數值)
test(3,y=2)    #正確
#test(3,x=2)    #錯誤

 

 

10.3.3預設參數

特點:1.調用函數的時候,預設參數非必須傳遞

2.若不傳遞預設參數值,則預設為預設的值。若傳遞預設參數值,則返回新傳遞的值

樣本1:

#!Author:lanhan
def test(x,y=2):
    print(x)
    print(y)
test(1,3)   #預設參數賦新值,返回最新值
test(1)     #預設參數沒有賦值,則返回預設參數值

 

 

10.3.4非固定參數(參數組)

不確定實參傳入多少個參數,形參使用非固定參數

樣本1:

#!Author:lanhan
def test(*args):
    print(args)
test(1,2,3,4,5,5)
test(*[1,2,3,4,5,5])   #*args=*[1,2,3,4,5,5]

 

 

 

樣本2:

#*args:接受N個位置參數,轉換成元組形式
def test(*args):
    print(args)
test(1,2,3,4,5,5)
test(*[1,2,3,4,5,5])   #*args=*[1,2,3,4,5,5]
樣本3:
#**kwargs:把N個關鍵字參數,轉換成字典的方式
def test2(**kwargs):
    print(kwargs)
    print(kwargs[‘name‘])
    print(kwargs[‘age‘])
    print(kwargs[‘sex‘])
test2(name=‘lanhan‘,age=8,sex=‘F‘)
test2(**{‘name‘:‘lanhan‘,‘age‘:8,‘sex‘:‘man‘})   #字典傳參

 

 

樣本4:

def test3(name,**kwargs):
    print(name)
    print(kwargs)
test3(‘lanhan‘,age=18,sex=‘m‘)   #與位置參數、關鍵字參數結合
樣本5:
def test4(name,age=18,**kwargs):
    print(name)
    print(age)
    print(kwargs)
test4(‘lanhan‘,12,sex=‘m‘,hobby=‘tesla‘)  #與預設參數結合

 

 

10.3.5局部變數

在子程式中定義的變數稱為局部變數,在程式的一開始定義的變數稱為全域變數。

全域變數範圍是整個程式,局部變數範圍是定義該變數的子程式。

當全域變數與局部變數同名時:

在定義局部變數的子程式內,局部變數起作用;在其它地方全域變數起作用

註:1.若要在子程式內強制更改全域變數,需用global聲明

2.全域變數是字典、集合、列表,在局部變數的子程式內可以更改

樣本1:

#!Author:lanhan
school = "oldboy edu."
def change_name(name):
    global school     #聲明局部更改全域變數
    school = "Mage Linux"
    print("before change",name)
    name = "Lanhan"      #這個函數就是這個變數的範圍
    age = 23
    print("after change",name,school)
name = ‘lanhan‘
change_name(name)
print("全域變數",name)     #
print("school:",school)

 

 

10.4 遞迴

在函數內部,可以調用其他函數。如果一個函數在內部調用自身本身,這個函數就是遞迴函式

遞迴特性:

1. 必須有一個明確的結束條件

2. 每次進入更深一層遞迴時,問題規模相比上次遞迴都應有所減少

3. 遞迴效率不高,遞迴層次過多會導致棧溢出(在電腦中,函數調用是通過棧(stack)這種資料結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返回,棧就會減一層棧幀。由於棧的大小不是無限的,所以,遞迴調用的次數過多,會導致棧溢出)

樣本1:

#!Author:lanhan
def calc(n):
    print(n)
    return calc(n+1)
calc(0)

 

 

 

 

樣本2:

def calc(n):
    print(n)
    if int(n/2) >0:
        return calc(int(n/2))
    print("-->",n)
calc(10)

 

 

 

10.5 高階函數

變數可以指向函數,函數的參數能接收變數,那麼一個函數就可以接收另一個函數作為參數,這種函數就稱之為高階函數

樣本1:

#!Author:lanhan
def add(a,b,f):
    return f(a)+f(b)
res = add(3,-6,abs)
print(res)

 

 

 

10.6 內建函數

python之路-10-函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.