def local1():
? ? num1=100
? ? print("local1中的num1的值位:%d"%num1)
def local2():
? ? num=102
? ? print("local2中num2的值位:%d"%num)
local1()
local2()
#總之,就是兩個不同函數(shù)內(nèi)部的變量名可以一樣。
---------------------------------------------------------------------------------------------------------------
函數(shù)之內(nèi)有這個變量result=100的,函數(shù)以外的相同的變量就不用了
def sum(a,b):
result=a+b
print("函數(shù)內(nèi)的result的值為:",result)
sum(100,20)
-----------------------------------------------------------------------------------------------
這種確實(shí)是不行啊,函數(shù)之內(nèi)確實(shí)不能用函數(shù)之外的變量
UnboundLocalError: local variable 'a' referenced before assignment
unbound英['?n'ba?nd]美[?n?ba?nd]
adj.無束縛的; <正>不負(fù)有義務(wù)的;
v.解開,解放( unbind的過去式和過去分詞 );
Many cultures still have fairly strict rules about women displaying?unbound?hair.
許多文化中對女子披散頭發(fā)仍有著相當(dāng)嚴(yán)格的規(guī)定。
a=1000
def test():
a+=1
? ? print(a)
test()
-----------------------------------------------------------------------------------------
global關(guān)鍵字來了。scale英[ske?l]美[skel]
n.規(guī)模; 比例(尺); 魚鱗; 級別;
vt.測量; 攀登; 刮去…的鱗片;
vi.衡量; 攀登; (鱗屑) 脫落; 生水垢;
[例句]However, he underestimates the?scale?of the?problem
然而,他低估了問題的嚴(yán)重性。
On a?global?scale, AIDS may well become the leading cause of infant?death.
艾滋病很可能會成為造成全球嬰兒死亡的首要原因。
a=1000#就是a完全可以當(dāng)參數(shù)傳進(jìn)來啊 ?。。?!不一定非要global
def test(a):
a+=1
? ? print(a)
test(a)
---------
a=1000
def test():
? ? global a
? ? a+=1
? ? print(a)
test()
——————-----------------------------------------------------------
使用nonlocal關(guān)鍵字可以在一個嵌套的函數(shù)中修改嵌套作用域中的變量
def test():
? ? x=1
? ? def test2():
? ? ? ? x=2
? ? test2()
? ? print(x)
test()
#輸出1
#這樣是正常啊,雖然在第二個函數(shù)中也定義了x=2,并且進(jìn)行了調(diào)用。但是是并列啊,就是和前面那個x=1是并列,不報錯已經(jīng)不錯了,肯定是按第一個x=1
-------------------------------------------------------------------------------------
def test():
x=1
? ? def test2():
nonlocal x
x=2
? ? test2()
print(x)
test()
#輸出2
就是不再是本地的變量了,nonlocal 了嘛