函式
封裝功能,提高應用的模塊性和代碼重用率
1. 定義函式
1.1 函式內的第一條陳述句是字串時,該字串就是檔案字串(docstring)
def my_fun():
'''我是檔案字串
函式內第一句是字串時
該字串就是檔案字串
'''
pass
print(my_fun.__doc__)
''' 運行結果:
我是檔案字串
函式內第一句是字串時
該字串就是檔案字串
'''
1.2 創建一個可以判斷一個整數是否是素數的函式
# 判斷某個整數是否是素數,是回傳Ture,不是回傳False
def isPrimer(num):
if num == 1:
return False
for i in range(2, num//2 + 1):
if num%i == 0:
return False
return True
# 判斷某個區間內的素數
def CircleIsPrimer(head, stop):
MyDict = {True: '素數', False: '非素數'}
for i in range(head, stop+1):
print(i, ' is ', MyDict[isPrimer(i)])
# 主函式
def main():
print(isPrimer(2))
CircleIsPrimer(1, 15)
# 呼叫主函式
main()
''' 運行結果
True
1 is 非素數
2 is 素數
3 is 素數
4 is 非素數
5 is 素數
6 is 非素數
7 is 素數
8 is 非素數
9 is 非素數
10 is 非素數
11 is 素數
12 is 非素數
13 is 素數
14 is 非素數
15 is 非素數
'''
1.3 創建一個可以輸出限定數值內的斐波拉契數列函式
def fib(num):
a, b = 0, 1
result = []
while a < num:
result.append(a)
a, b =b, a + b
return result
print(fib(10))
''' 運行結果
[0, 1, 1, 2, 3, 5, 8]
'''
2. 引數傳遞
在Python中,物件有不同型別的區分,變數沒有型別
2.1 默認引數,定義函式時,需要從右往左給引數默認值,呼叫函式時,如果沒有傳遞引數,則會使用默認引數
def loves(who,how='sincerely love',what='Python',why='Only because I love it'):
print(who, end=' ')
print(how, end=' ')
print(what)
print(why)
return
loves('I')
''' 運行結果
I sincerely love Python
Only because I love it
'''
2.2 關鍵字,使用關鍵字引數允許函式呼叫時引數的順序與宣告時不一致
# 判斷某個整數是否是素數,是回傳Ture,不是回傳False
def isPrimer(num):
if num == 1:
return False
for i in range(2, num//2 + 1):
if num%i == 0:
return False
return True
# 判斷某個區間內的素數
def CircleIsPrimer(head, stop):
MyDict = {True: '素數', False: '非素數'}
for i in range(head, stop+1):
print(i, ' is ', MyDict[isPrimer(i)])
CircleIsPrimer(stop = 15, head = 1)
''' 運行結果
1 is 非素數
2 is 素數
3 is 素數
4 is 非素數
5 is 素數
6 is 非素數
7 is 素數
8 is 非素數
9 is 非素數
10 is 非素數
11 is 素數
12 is 非素數
13 is 素數
14 is 非素數
15 is 非素數
'''
2.3 不定長引數,加了*的引數會以元組的形式匯入,存放所有未命名的變數引數,加了**的引數會以字典的形式匯入
# 2.3.1 以元組形式匯入,包含形參串列之外的位置引數
def isLovePython(who, how, what, *why):
print(who, end=' ')
print(how, end=' ')
print(what)
print(why)
return
isLovePython('I', 'love', 'Python', 'only', 'because', 'I', 'love', 'it')
''' 運行結果
I love Python
('only', 'because', 'I', 'love', 'it')
'''
# 2.3.2 以字典形式匯入,包含已定義形參對應之外的所有關鍵字引數
def isLovePython(**lovePython):
print(lovePython)
return
isLovePython(who='I', how='sincerely love', what='Python')
''' 運行結果
{'who': 'I', 'how': 'sincerely love', 'what': 'Python'}
'''
# 2.3.3 二者組合使用,*形參 必須在 **形參之前
def LovePython(who_, *how_, **info):
print(who_)
print(how_)
print(info)
return
LovePython('I', 'need', 'Python', who='live', how='is short')
''' 運行結果
I
('need', 'Python')
{'who': 'live', 'how': 'is short'}
'''
2.4 強制位置引數,限制引數的傳遞方式
def my_fun(a, b, /, c, d, *, e, f):
pass
# a,b 必須是位置形參
# c,d 位置形參或關鍵字形參
# e,f 必須是關鍵字形參
3. 解包實參串列
3.1 用*把實參從串列或元組中解包出來
love = ['I', 'need', 'Python']
def Printf(who: str, how: str, what: str = 'MySQL') -> None:
print(who, '', how, '', what)
return
Printf(*love)
''' 運行結果
I need Python
'''
3.2 用**把實參從字典中解包出來
love = {'who': 'I', 'how': 'need', 'what': 'Python'}
def Printf(who: str, how: str, what: str = 'MySQL') -> None:
print(who, '', how, '', what)
return
Printf(**love)
''' 運行結果
I need Python
'''
4. Lambda 運算式
常規定義函式的語法糖,只能是單個運算式
# 4.1 把匿名函式作為傳遞的實參
# 案例1:把 python、pytorch、pandas 篩選出來
love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
loveAI = filter(lambda x: x[0] == 'p', love)
print(list(loveAI))
''' 運行結果
['python', 'pytorch', 'pandas']
'''
# 案例2:字母全變大寫
love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
love = map(lambda x: x.upper(), love)
print(list(love))
''' 運行結果
['PYTHON', 'PHP', 'PYTORCH', 'MYSQL', 'PANDAS']
'''
# 4.2 把匿名函式作為函式回傳值
love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
def LoveAI():
return lambda x: x[0] == 'p'
love_AI = LoveAI()
loveAI = filter(love_AI, love)
print(list(loveAI))
''' 運行結果
['python', 'pytorch', 'pandas']
'''
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500737.html
標籤:Python
上一篇:關于shape和axis的使用
