定義(關鍵字def):
編程語言中函式定義:函式是邏輯結構化和程序化的一種編程方法(函式是指將一組陳述句的集合通過一個名字(函式名)封裝起來,要想執行這個函式,只需呼叫其函式名即可)
函式特性:
1.減少重復代碼
2.使程式變得可擴展
3.使程式變得易維護
格式:
1 def func1(): # 函式名func1 2 """這里是注釋""" 3 代碼塊 4 return 值
注:程序是缺少回傳值的函式(在python中,程序實際是回傳值為None的函式);想要查看回傳值,可以將呼叫函式的結果賦給一個變數
1 import time 2 3 4 def logger(): 5 """追加內容至檔案a中,并標識時間""" 6 time_format = '%Y-%m-%d %X' 7 time_current = time.strftime(time_format) 8 with open('a.txt', "a+", encoding='utf-8') as f: 9 f.write(f'{time_current} Yesterday once more-昨日重現\n') 10 f.close() 11 def test1(): 12 print("In the test1") 13 logger() 14 def test2(): 15 print("In the test2") 16 logger() 17 def test3(): 18 print("In the test3") 19 logger() 20 test1() # 呼叫函式test1 21 test2() # 呼叫函式test2 22 test3() # 呼叫函式test3函式特性實體
可以回傳的值:
1.什么都不寫:回傳None
2.return 0:回傳0
3.return 1,’hello’,[‘sjc’,’wk’],{‘name’:’sjc’}:回傳元組(1,’hello’,[‘sjc’,’wk’],{‘name’:’sjc’})
為什么要有回傳值:后續其他邏輯可能會根據回傳值的不同進行不一樣的操作
def test1(): print('in the test1') def test2(): print('in the test2') return 0 def test3(): print('in the test3') return 1, 'hello', ['sjc', 'wk'], {'name': 'sjc'} x = test1() y = test2() z = test3() print(x, '\n', y, '\n', z, sep='')return
1 in the test1 2 in the test2 3 in the test3 4 None 5 0 6 (1, 'hello', ['sjc', 'wk'], {'name': 'sjc'})output
形參與實參:
形參:變數只有在被呼叫時才分配記憶體單元,在呼叫結束時,即刻釋放所分配的記憶體單元,因此,形參只在函式內部有效,函式呼叫結束回傳主呼叫函式后則不能再使用該形參變數
實參:可以是常量、變數、運算式、函式等,無論實參是何種型別的量,在進行函式呼叫時,它們都必須有確定的值,以便把這些值傳送給形參,因此應預先用賦值,輸入等辦法使引數獲得確定值
注意:傳參時實參與形參是一一對應的(位置引數),若想不按順序傳入,需要用 傳參=實參(關鍵字引數)的方式,但是,關鍵字引數必須位于位置引數后方
默認引數:
呼叫函式的時候,默認引數非必須傳遞,不傳遞時則取默認值,傳遞則取傳遞值
引陣列:
形參以*開始+一個變數名,一般為*args(規范,盡量別改),會把所有傳入引數放入一個元組,只接收位置引數
想傳入字典呢?試試**kwargs且用關鍵字引數傳參(或者用**+字典的方式傳參)
再試試引陣列與引陣列、形參、默認引數結合
注意:引陣列盡量往后放
1 def test(x, y): 2 print(x) 3 print(y) 4 5 6 test(1, 2) 7 test(y="關鍵引數y", x='關鍵引數x') 8 9 10 def test2(x, y='我是默認引數'): 11 print(x) 12 print(y) 13 14 15 test2(1) 16 test2(y='賦值后默認引數會改', x=4) 17 18 19 def test3(*args): 20 print(args) 21 22 23 test3(1, 2, 4, 8, 9) 24 25 26 # 傳入引數個數不固定時 27 # *args:把N個位置引數轉換成元組的方式 28 def test4(x, *args): 29 print(x) 30 print(args) 31 32 33 test4(5, 6, '引數不固定', 8, 10) 34 test4(*[5, 6, '引數不固定', 8, 10]) # args = tuple([5, 6, '引數不固定', 8, 10]) 35 36 37 # 把N個關鍵字引數轉換成字典的方式 38 def test5(**kwargs): 39 print(kwargs) 40 print(kwargs['name']) # 取字典中key為name的value(key不存在會報錯) 41 42 43 test5(name='sjc', age=18) 44 test5(**{'name': 'sjc', 'age': 18, 'size': 'unknown'}) 45 46 47 def test6(name, age=18, *args, **kwargs): 48 print(name) 49 print(age) 50 print(args) 51 print(kwargs) 52 53 54 test6('SJC', 12, 5, hobby='game')parameters
1 2 關鍵引數x 關鍵引數y 1 我是默認引數 4 賦值后默認引數會改 (1, 2, 4, 8, 9) 5 (6, '引數不固定', 8, 10) 5 (6, '引數不固定', 8, 10) {'name': 'sjc', 'age': 18} sjc {'name': 'sjc', 'age': 18, 'size': 'unknown'} sjc SJC 12 (5,) {'hobby': 'game'} Process finished with exit code 0output
區域變數:
只在函式中生效(在函式內部代碼塊位置定義的變數)/可用global將區域變數改為全域變數(盡量別用)
全域變數:
在整個代碼頂層定義的變數
當全域變數與區域變數同名時:在區域變數內修改變數值,當變數是字串或整型時,呼叫函式是修改后的值,但呼叫結束后全域變數是不變的(在定義區域變數的子程式內,區域變數起作用;在其它地方全域變數起作用);當變數是串列等型別時,使用區域變數修改串列內某些值,呼叫函式結束后全域變數也隨之改變,
1 # def change_name(name): 2 # print('before change', name) 3 # name = 'SJC' # 這個函式就是這個變數的作用域 4 # print('after change', name) 5 # 6 # name = 'sjc' 7 # change_name(name) 8 # print(name) 9 10 name = 'SJC' 11 name1 = [1, 2, 3] 12 13 14 def change_name(): 15 name = 'sjc' 16 name1[0] = 8 17 print(name, name1) 18 19 20 print(name, name1) 21 change_name() 22 print(name, name1)variable
1 SJC [1, 2, 3] 2 sjc [8, 2, 3] 3 SJC [8, 2, 3]output
遞回:
在函式內部,可以呼叫其他函式,如果一個函式在內部呼叫自身本身,這個函式就是遞回函式,
遞回特性:
1.必須有一個明確的結束條件
2.每次進入更深一層遞歸時,問題規模相比上次遞回都應有所減少
3.遞回效率不高,遞回層次過多會導致堆疊溢位(在計算機中,函式呼叫是通過堆疊(stack)這種資料結構實作的,每當進入一個函式呼叫,堆疊就會加一層堆疊幀,每當函式回傳,堆疊就會減一層堆疊幀,由于堆疊的大小不是無限的,所以,遞回呼叫的次數過多,會導致堆疊溢位)
1 def calc(n): 2 if n/2 > 0: 3 print(n) 4 return calc(int(n/2)) 5 print(n) 6 7 8 calc(10)recursion
1 10 2 5 3 2 4 1 5 0output
函式式編程:知乎“什么是函式式編程思維?”
高階函式:
變數可以指向函式,函式的引數能接收變數,那么一個函式就可以接收另一個函式作為引數,這種函式就稱之為高階函式,
1 def add(a, b, f): 2 return f(a)+f(b) 3 4 5 res = add(3, -6, abs) 6 print(res)higher-order
上例輸出為 9
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/5972.html
標籤:Python
