10 - 函數進階📄目錄1 作用域1.1 全局變量1.2 局部變量1.3 global1.4 nonlocal2 匿名函數2.1 基本語法:2.2 lambda的參數形式2.2.1 無參數2.2.2 一個參數2.2.3 默認參數2.2.4 關鍵字參數2.3 lambda結合if判斷3 內置函數3.1 內置函數一3.1.1 abs():返回絕對值3.1.2 sum():求和3.2 內置函數二3.2.1 min():求最小值3.2.2 max():求最大值3.2.3 zip():將可迭代對象作為參數,將對象中對應的元素打包成一個個元組3.2.4 map():映射函數。可以對可迭代對象中的每一個元素進行映射,分別去執行3.2.5 reduce():先把對象中的兩個元素取出,計算出一個值然後保存着,接下來把這個計算值跟第三個元素進行計算4 拆包導航連結:
💡 含義:指的是變量生效的範圍,分為兩種,分別是全局變量和局部變量
💡 函數外部定義的變量,在整個文件中都是有效的

xxxxxxxxxxa = 100 # 全局變量def test1(): print('這是test1中a的值:', a)def test2(): a = 120 # 局部變量 print('這是test2中a的值:', a)print('調用函數前a的值:', a)test1()test2()print('調用函數後a的值:', a)輸出結果:
xxxxxxxxxx調用函數前a的值: 100這是test1中a的值: 100這是test2中a的值: 120調用函數後a的值: 100❗ a的值沒有被覆蓋是因為函數內部如果要使用變量,會先從函數內部找,有的話就直接使用,沒有就會到函數外面找
💡 函數內部定義的變量,從定義位置開始到函數定義結束位置有效
作用:在函數體內部,臨時保存數據,即當函數調用完成之後,就銷毀局部變量

xxxxxxxxxxdef test3(): num = 10 # 局部變量 print('num:',num)test3()# print('num:',num) # 報錯,局部變量只能在被定義的函數中使用,函數外部不能使用輸出結果:
xxxxxxxxxxnum: 10
兩個函數之間有命名相同的變量沒有影響,因為它們所在的作用域不一樣
xxxxxxxxxxdef test4(): num = 10 print('test4中的num:',num)test4()def test5(): num = 12 print('test5中的num:', num)test5()輸出結果:
xxxxxxxxxxtest4中的num: 10test5中的num: 12💡 在函數內部修改全局變量的值,可以使用global關鍵字
將變量聲明為全局變量
語法格式:global 變量名

xxxxxxxxxxa = 100def test6(): print('這是test6中a的值:', a)def test7(): global a a = 120 print('這是test7中a的值:', a)print('調用函數前a的值:', a)test6()test7()print('調用函數後a的值:', a)輸出結果:
xxxxxxxxxx調用函數前a的值: 100這是test6中a的值: 100這是test7中a的值: 120調用函數後a的值: 120
xxxxxxxxxxdef study(): global name, age name = 'python基礎' age = 20 print(f'{age}歲的我們在學習{name}')study()print(age, name)def work(): print(name)work()輸出結果:
xxxxxxxxxx20歲的我們在學習python基礎20 python基礎python基礎💡 總結:global關鍵字可以對全局變量進行修改,也可以在局部作用域中聲明一個全局變量
💡 作用:用來聲明外層的局部變量,只能在嵌套函數中使用
在外部函數先進行聲明,內部函數中進行nonlocal聲明

xxxxxxxxxxa = 10 # 全局變量def outer(): # 外函數 a = 5 #局部變量 def inner(): # 內函數 a = 20 def inner2(): nonlocal a a = 30 print('inner2函數中a的值:', a) inner2() print('inner函數中a的值:', a) inner() print('outer函數中a的值:',a)outer()print(f'全局中a的值:{a}')輸出結果:
xxxxxxxxxxinner2函數中a的值: 30inner函數中a的值: 30outer函數中a的值: 5全局中a的值:10💡 總結:nonlocal只能對上一級進行修改
💡
xxxxxxxxxx# 定義:函數名 = lambda 形參 : 返回值(表達式)# 調用:結果 = 函數名(實參)
xxxxxxxxxx# 普通函數def add(b,c): return b+cprint(add(3,4))# 匿名函數add = lambda b,c: b+c # b,c就是匿名函數的形參,a+b是返回值的表達式# lambda不需要寫return來返回值,表達式本身結果就是返回print(add(4,5))輸出結果:
xxxxxxxxxx79💡
xxxxxxxxxx函數名 = lambda 形參 : 返回值(表達式)
xxxxxxxxxxfunc1 = lambda : '一桶水果茶'print(func1())輸出結果:
xxxxxxxxxx一桶水果茶
xxxxxxxxxxfunc2 = lambda n1:n1print(func2('一桶水果茶'))輸出結果:
xxxxxxxxxx一桶水果茶
xxxxxxxxxxfunc3 = lambda n1, age = 18 : (name,age)print(func3('Antonio'))print(func3('Antonio',20))func4 = lambda n1, n2, n3 = 20 : n1 + n2 + n3print(func4(1,4))# 默認參數必須寫在非默認參數後面輸出結果:
xxxxxxxxxx('python基礎', 18)('python基礎', 20)25
xxxxxxxxxxfunc5 = lambda **kwargs:kwargsprint(func5(name = 'antonio', age = 18))輸出結果:
xxxxxxxxxx{'name': 'antonio', 'age': 18}
xxxxxxxxxxa = 5b = 8# 為真結果 if 條件 else 為假結果print('a比b小') if a < b else print('a>=b')comp = lambda c,d: 'c比d小' if c < d else 'c大於等於d'print(comp(8,5))輸出結果:
xxxxxxxxxxa比b小c大於等於d💡 特點:lambda只能實現簡單的邏輯,如果邏輯複雜且代碼量較大,不建議使用lambda,降低代碼的可讀性,為後期的代碼維護增加困難

xxxxxxxxxx# 查看所有的內置函數import builtinsprint(dir(builtins))# 大寫字母開頭一般是內置常量名,小寫字母開頭一般是內置函數名輸出結果:
xxxxxxxxxx['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
xxxxxxxxxxprint(abs(-10))print(abs(10))輸出結果:
xxxxxxxxxx1010
xxxxxxxxxxgp1 = (1, 2, 3, 4, 5)print(sum(gp1)) # 其中必須要是可迭代對象(基本就是列表、元組和集合),且只能用於數字求和gp2 = (1.1, 2, 3, 4, 5)print(sum(gp2)) # 運算時,只要有一個元素為浮點數,那結果就會是浮點數輸出結果:
xxxxxxxxxx1515.1
xxxxxxxxxxprint(min(4,2,6,5))輸出結果:
xxxxxxxxxx2
xxxxxxxxxxprint(max(4,2,6,5))print(max(4,2,-6,5, key = abs)) # 傳入了求絕對值函數,參數會先求絕對值再取最大者輸出結果:
xxxxxxxxxx6-6
xxxxxxxxxxli = [1,2,3,4]li2 = ['a','b','c']print(zip(li,li2))# 第一種方式:通過for循環for i in zip(li,li2): print(i, type(i)) # 如果元素個數不一致,按照長度最短的返回# 第二種方式:轉換成列表打印print(list(zip(li,li2)))# print(list(zip(li,3))) #報錯# 注意:必須是可迭代對象輸出結果:
xxxxxxxxxx<zip object at 0x105044340>(1, 'a') <class 'tuple'>(2, 'b') <class 'tuple'>(3, 'c') <class 'tuple'>[(1, 'a'), (2, 'b'), (3, 'c')]💡 map(func,iter1):func--自己定義的函數、iter1--要放進去的可迭代對象

xxxxxxxxxxli3 = [1, 2, 3, 4, 5]# def funa(x):# return x*5funa = lambda x: x*5mp = map(funa, li3) # 注意‼️:只要寫函數名,不需要加上小括號print(mp)# for i in mp:# print(i)print(list(mp)) # 兩種不能同時執行,否則第二種會返回空輸出結果:
xxxxxxxxxx<map object at 0x1055bfe80>[5, 10, 15, 20, 25]
xxxxxxxxxx# 需要先導包from functools import reduce# reduce(function, sequence) # function--函數:必須是有兩個參數的函數,sequence--序列:可迭代對象li4 = [1, 2, 3, 4, 5]def add(x,y): return x * (2 + y)res = reduce(add,li4)# 使res等於計算結果,方便保存和輸出print(res)輸出結果:
xxxxxxxxxx840💡 含義:對於函數中的多個返回數據,去掉元組、列表或者字典,直接獲取裡面數據的過程

xxxxxxxxxxtua = (1, 2, 3, 4, 5)print(tua)# 方法一a, b, c, d, e = tuaprint(a, b, c, d, e)# 要求元組內的個數與接收的變量個數相同,對象內有多少個數據就需要定義多少個變量接收# 一般在獲取元組值的時候使用# 方法二a, *b = tuaprint(a, b) # 未拆包print(a, *b) # 順便把列表b也拆包輸出結果:
xxxxxxxxxx(1, 2, 3, 4, 5)1 2 3 4 51 [2, 3, 4, 5]1 2 3 4 5
功能:一般在函數調用時使用
xxxxxxxxxxdef func1(f,g,*args): print(f,g) print(args,type(args))func1(1,2,3,4,5)arg = (2,3,4,5,6)func1(*arg)輸出結果:
xxxxxxxxxx1 2(3, 4, 5) <class 'tuple'>2 3(4, 5, 6) <class 'tuple'>| 目的地 | 超連結 |
|---|---|
| 首頁 | 返回主頁 |
| Python學習 | Python學習 |
| 上一篇 | 09 - 函數基礎 |
| 下一篇 | 11 - 異常、模塊、包 |