封裝功能,Improve application modularity and code reuse
1.1 函數內的第一條語句是字符串時,該字符串就是文檔字符串(docstring)
def my_fun():
'''我是文檔字符串
When the first sentence in the function is a string
該字符串就是文檔字符串
'''
pass
print(my_fun.__doc__)
''' 運行結果:
我是文檔字符串
When the first sentence in the function is a string
該字符串就是文檔字符串
'''
1.2 Create a function that can determine whether an integer is prime
# Check if an integer is prime,是返回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
# Determine the prime numbers in a range
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 Create a Fibonacci sequence function that outputs a limited number of values
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]
'''
在Python中,對象有不同類型的區分,變量沒有類型
2.1 默認參數.定義函數時,Parameter default values need to be given from right to left,調用函數時,如果沒有傳遞參數,則會使用默認參數
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 關鍵字.使用關鍵字參數允許函數調用時參數的順序與聲明時不一致
# Check if an integer is prime,是返回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
# Determine the prime numbers in a range
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 以元組形式導入,Contains positional parameters outside of the formal parameter list
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 以字典形式導入,Contains all keyword arguments other than those corresponding to the defined formal parameters
def isLovePython(**lovePython):
print(lovePython)
return
isLovePython(who='I', how='sincerely love', what='Python')
''' 運行結果
{'who': 'I', 'how': 'sincerely love', 'what': 'Python'}
'''
# 2.3.3 二者組合使用,*形參 必須在 **before the parameter
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 強制位置參數.Restrict how parameters are passed
def my_fun(a, b, /, c, d, *, e, f):
pass
# a,b Must be a positional parameter
# c,d Positional or keyword parameters
# e,f Must be a keyword parameter
3.1 用*Unpack arguments from a list or tuple
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 用**Unpack the arguments from the dictionary
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
'''
Syntactic sugar for routinely defined functions,只能是單個表達式
# 4.1 Pass anonymous functions as arguments
# 案例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:All letters are capitalized
love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
love = map(lambda x: x.upper(), love)
print(list(love))
''' 運行結果
['PYTHON', 'PHP', 'PYTORCH', 'MYSQL', 'PANDAS']
'''
# 4.2 Use anonymous functions as function return values
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']
'''