💡 含義:指的是變量生效的範圍,分為兩種,分別是全局變量和局部變量
💡 函數外部定義的變量,在整個文件中都是有效的
xxxxxxxxxx
a = 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的值沒有被覆蓋是因為函數內部如果要使用變量,會先從函數內部找,有的話就直接使用,沒有就會到函數外面找
💡 函數內部定義的變量,從定義位置開始到函數定義結束位置有效
作用:在函數體內部,臨時保存數據,即當函數調用完成之後,就銷毀局部變量
xxxxxxxxxx
def test3():
num = 10 # 局部變量
print('num:',num)
test3()
# print('num:',num) # 報錯,局部變量只能在被定義的函數中使用,函數外部不能使用
輸出結果:
xxxxxxxxxx
num: 10
兩個函數之間有命名相同的變量沒有影響,因為它們所在的作用域不一樣
xxxxxxxxxx
def test4():
num = 10
print('test4中的num:',num)
test4()
def test5():
num = 12
print('test5中的num:', num)
test5()
輸出結果:
xxxxxxxxxx
test4中的num: 10
test5中的num: 12
💡 在函數內部修改全局變量的值,可以使用global關鍵字
將變量聲明為全局變量
語法格式:global 變量名
xxxxxxxxxx
a = 100
def 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
xxxxxxxxxx
def study():
global name, age
name = 'python基礎'
age = 20
print(f'{age}歲的我們在學習{name}')
study()
print(age, name)
def work():
print(name)
work()
輸出結果:
xxxxxxxxxx
20歲的我們在學習python基礎
20 python基礎
python基礎
💡 總結:global關鍵字可以對全局變量進行修改,也可以在局部作用域中聲明一個全局變量
💡 作用:用來聲明外層的局部變量,只能在嵌套函數中使用
在外部函數先進行聲明,內部函數中進行nonlocal聲明
xxxxxxxxxx
a = 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}')
輸出結果:
xxxxxxxxxx
inner2函數中a的值: 30
inner函數中a的值: 30
outer函數中a的值: 5
全局中a的值:10
💡 總結:nonlocal只能對上一級進行修改
💡
xxxxxxxxxx
# 定義:
函數名 = lambda 形參 : 返回值(表達式)
# 調用:
結果 = 函數名(實參)
xxxxxxxxxx
# 普通函數
def add(b,c):
return b+c
print(add(3,4))
# 匿名函數
add = lambda b,c: b+c # b,c就是匿名函數的形參,a+b是返回值的表達式
# lambda不需要寫return來返回值,表達式本身結果就是返回
print(add(4,5))
輸出結果:
xxxxxxxxxx
7
9
💡
xxxxxxxxxx
函數名 = lambda 形參 : 返回值(表達式)
xxxxxxxxxx
func1 = lambda : '一桶水果茶'
print(func1())
輸出結果:
xxxxxxxxxx
一桶水果茶
xxxxxxxxxx
func2 = lambda n1:n1
print(func2('一桶水果茶'))
輸出結果:
xxxxxxxxxx
一桶水果茶
xxxxxxxxxx
func3 = lambda n1, age = 18 : (name,age)
print(func3('Antonio'))
print(func3('Antonio',20))
func4 = lambda n1, n2, n3 = 20 : n1 + n2 + n3
print(func4(1,4))
# 默認參數必須寫在非默認參數後面
輸出結果:
xxxxxxxxxx
('python基礎', 18)
('python基礎', 20)
25
xxxxxxxxxx
func5 = lambda **kwargs:kwargs
print(func5(name = 'antonio', age = 18))
輸出結果:
xxxxxxxxxx
{'name': 'antonio', 'age': 18}
xxxxxxxxxx
a = 5
b = 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))
輸出結果:
xxxxxxxxxx
a比b小
c大於等於d
💡 特點:lambda只能實現簡單的邏輯,如果邏輯複雜且代碼量較大,不建議使用lambda,降低代碼的可讀性,為後期的代碼維護增加困難
xxxxxxxxxx
# 查看所有的內置函數
import builtins
print(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']
xxxxxxxxxx
print(abs(-10))
print(abs(10))
輸出結果:
xxxxxxxxxx
10
10
xxxxxxxxxx
gp1 = (1, 2, 3, 4, 5)
print(sum(gp1)) # 其中必須要是可迭代對象(基本就是列表、元組和集合),且只能用於數字求和
gp2 = (1.1, 2, 3, 4, 5)
print(sum(gp2)) # 運算時,只要有一個元素為浮點數,那結果就會是浮點數
輸出結果:
xxxxxxxxxx
15
15.1
xxxxxxxxxx
print(min(4,2,6,5))
輸出結果:
xxxxxxxxxx
2
xxxxxxxxxx
print(max(4,2,6,5))
print(max(4,2,-6,5, key = abs)) # 傳入了求絕對值函數,參數會先求絕對值再取最大者
輸出結果:
xxxxxxxxxx
6
-6
xxxxxxxxxx
li = [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--要放進去的可迭代對象
xxxxxxxxxx
li3 = [1, 2, 3, 4, 5]
# def funa(x):
# return x*5
funa = lambda x: x*5
mp = 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)
輸出結果:
xxxxxxxxxx
840
💡 含義:對於函數中的多個返回數據,去掉元組、列表或者字典,直接獲取裡面數據的過程
xxxxxxxxxx
tua = (1, 2, 3, 4, 5)
print(tua)
# 方法一
a, b, c, d, e = tua
print(a, b, c, d, e)
# 要求元組內的個數與接收的變量個數相同,對象內有多少個數據就需要定義多少個變量接收
# 一般在獲取元組值的時候使用
# 方法二
a, *b = tua
print(a, b) # 未拆包
print(a, *b) # 順便把列表b也拆包
輸出結果:
xxxxxxxxxx
(1, 2, 3, 4, 5)
1 2 3 4 5
1 [2, 3, 4, 5]
1 2 3 4 5
功能:一般在函數調用時使用
xxxxxxxxxx
def 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)
輸出結果:
xxxxxxxxxx
1 2
(3, 4, 5) <class 'tuple'>
2 3
(4, 5, 6) <class 'tuple'>
目的地 | 超連結 |
---|---|
首頁 | 返回主頁 |
Python學習 | Python學習 |
上一篇 | 09 - 函數基礎 |
下一篇 | 11 - 異常、模塊、包 |