1.函式定義
??函式就是將完成一件事情的步驟封裝在一起并得到最終的結果;
??函式名代表了這個函式要做的事情;
??函式體是實作函式功能的流程;
??添加一個函式也被叫做實作了一個方法或功能;
??函式可以幫助我們重復使用一些操作步驟;
2.def
??通過關鍵字def定義函式;
??def name(args...):
????print('')
??return 是將函式結果回傳的關鍵字;
??return只能在函式體中使用;
??return支持回傳所有python型別;
??有回傳值的函式可以直接賦值給一個變數;
??def add(a, b):
????c=a+b
????return c # 出現retuen代表函式執行結束,后面有陳述句也不會執行了
def multiplication(a, b):
re = a * b
return re
print('test')
result = multiplication(3, 4) # 函式回傳值可以直接賦值給變數
print(result)
'''
12 return后的陳述句不會被執行
'''
def no_re():
print('無回傳的函式')
no_r = no_re()
print(no_r) # 函式無回傳時,默認是None
'''
無回傳的函式
None
'''
def test():
for i in range(4):
print(i)
if i == 2:
return i
t = test()
print(t)
'''
0
1
2
2
# return后回圈結束,函式結束;只列印到2,且函式回傳值2
'''
3.函式的引數
??必傳引數(位置引數),函式中定義的沒有默認值的引數,在呼叫函式時若不傳則會報錯;
??在定義函式時,引數后無等號和默認值;
??且傳參時,實際值的順序與定義的引數順序要一致;
????def add(a, b)
??默認引數,定義函式時,定義的引數有默認值,通過賦值陳述句給他一個值;
??如果呼叫函式時,為默認引數傳遞了新值,函式會使用新傳入的值;
????def add(a, b=1)
def add(a, b, c=4):
return a+b+c
re = add(1, 2) # 使用c的默認值
print(re) # 7
re2 = add(1, 2, 5) # 使用c的新值
print(re2) # 8
# 注意,默認引數一定在位置引數之后,否則會報錯
def add2(a, b=3, c):
return a+b+c
add2(1, 3, 2)
'''
File "D:\python_exercise\test.py", line 566
def add2(a, b=3, c):
^
SyntaxError: non-default argument follows default argument
'''
??不確定引數--可變引數,沒有固定的引數名和數量(提前不知道要傳的引數名和數量);
??def add(*args, **kwargs)
??*args保存多余實參,保存為元組、**kwargs保存多余的帶有變數名的實參,保存為字典;
def add(a, b, c=4, *args, **kwargs):
print(a)
print(b)
print(c)
print(args, type(args))
print(kwargs, type(kwargs))
add(1, 2, 3, 4, 5, d=3, e=4)
'''
1
2
3 # 3給了默認引數c,后面再有的剩余實際引數保存為元組了
(4, 5) <class 'tuple'>
{'d': 3, 'e': 4} <class 'dict'>
# 后面就可以使用元組、字典的方法處理args和kwargs了
'''
def test(*args, **kwargs):
print(args)
print(kwargs)
test((2, 3), {'name': 'll', 'age': 23})
'''
((2, 3), {'name': 'll', 'age': 23})
{}
'''
# 可以發現*args是將多余實參都放到了元組中
# 如果就想對應傳遞元組和字典,可以在實參前加*和**
test(*(2, 3), **{'name': 'll', 'age': 23})
'''
(2, 3)
{'name': 'll', 'age': 23}
'''
def add3(a, b, c):
return a+b+c
tuple_test = (23, 45, 0)
re = add3(*tuple_test) # 此時也可以借助*tuple對實參進行解包
print(re) # 68
??引數的規則,
??多引數一般添加順序 :def add(a, b=1, *args, **kwargs) ,
??
??上面的例子可以看到python中函式引數沒有定義型別,
??其實在py3.7后可以為引數定義型別,但只是用于肉眼上的查看;
??def person(name:str, age:int=33):
????print(name, age)
def add(a: int, b: int, *args: int):
print(a, b, args)
add(1, 2, 4, 'rt') # 1 2 (4, 'rt')
# 雖然傳遞的引數不符合資料型別的要求,但可以正常執行,指定型別只是起提示功能
??且pycharm中也會有提示標注
??
4.全域變數和區域變數
??python腳本最上層代碼塊的變數,就是全域變數;全域變數可以在函式中讀取使用;
??區域變數:只能在區域使用的變數,比如函式體內的變數只能在函式內使用;
name = 'll' # 定義一個全域變數
def test():
print('函式體內'+name)
test() # 函式體內ll (函式體內可以直接使用全域變數)
def test2():
age = 13
print(age)
test2() # 13
print(age) # NameError: name 'age' is not defined (區域變數只能在區域使用)
def test3():
name = 'tt'
print(name)
test3() # tt
print(name) # ll (全域變數未被函式修改,函式只能使用全域變數,不能修改)
??可以使用global關鍵字,在函式內修改全域變數;(但在作業中不建議使用global對全域變數進行修改)
name = 'll' # 定義一個全域變數
def test():
global name
name = 'tt'
test()
print(name) # tt
??當全域變數值是字典或串列時,函式內可以直接修改其值;
name_list = ['ll', 'tt'] # 定義一個全域變數
def test():
name_list.append('rr')
test()
print(name_list) # ['ll', 'tt', 'rr']
5.函式的遞回
??一個函式不停的將自己反復執行;
??def test(a):
????print(a)
????return test(a) 通過回傳值,直接執行函式自身,就可以達到遞回的效果;
??避免濫用遞回,一定要設定滿足后退出遞回的條件,小心記憶體溢位;
??能用遞回解決的問題必須滿足兩個條件:
????1.可以通過遞回呼叫來縮小問題規模,且新問題與原問題有著相同的形式;
????2.存在一種簡單情形,使用該簡單情形可退出遞回;
count = 0
def test():
global count
count += 1
if count != 5:
print('繼續執行函式')
return test()
else:
print('執行結束')
test()
'''
繼續執行函式
繼續執行函式
繼續執行函式
繼續執行函式
執行結束
'''
??兩個經典的遞回案例,階乘和斐波那契數列;
'''
階乘
n! = 1*2*3*...*n
f(n) = n * f(n-1)
且f(1)=1
'''
def test(n):
if n == 1:
return 1
return n * test(n-1)
re = test(6)
print(re) # 720
'''
斐波那契數列(黃金分割數列)
數列從0開始,數列前兩項是0,1,第三項開始每一項是前兩項的和
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)
'''
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
return fib(n-1) + fib(n-2)
# 求數列的第9項
re2 = fib(9)
print(re2) # 34
# 列印20項
for i in range(20):
if i == 19:
print(fib(i), end=',')
else:
print(fib(i), end=',')
# 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181
6.匿名函式lambda
??可以定義一個輕量化的函式,處理一些簡單操作;
??即用即洗掉,適合需要完成一項功能,但此功能只在此一處使用;
??無引數lambda, f = lambda : value ; f()呼叫;lambda函式自帶return關鍵字,此時回傳值是value;
??有引數lambda, f = lambda x,y: x*y ; f(3, 4)呼叫; 此時回傳值是x*y的值12;
test = lambda: 34
print(test()) # 34
test2 = lambda x, y: x > y
re = test2(4, 6)
print(re) # False
test3 = lambda x, y=4: x + y
re = test3(4, 6)
print(re) # 10
# 此時可以再來看串列的sort(key)方法,key引數值就是函式、可以指定排序的參考值,此處就可以使用lambda函式的寫法
name_list = [
{'name': 'll', 'age': 34},
{'name': 'tt', 'age': 4},
{'name': 'rr', 'age': 24}
]
# 按照字典中age對應的值排序
name_list.sort(key=lambda x: x['age'])
print(name_list) # [{'name': 'tt', 'age': 4}, {'name': 'rr', 'age': 24}, {'name': 'll', 'age': 34}]
??
總結
??
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/523874.html
標籤:Python
上一篇:1.簡介
