[英]Why the global variable is not working in the different functions in Python?
我是Python的新手。 我寫了如下代碼,只是為了練習。
i=1
def wrte():
global i
while i<5:
print "%s .Line..\n" %i
i+=1
def appnd():
j=i
while i in range(i,j+3):
print "%s .Line..\n" %i
i+=1
def Main():
wrte()
appnd()
Main()
輸出如下
1 .Line..
2 .Line..
3 .Line..
4 .Line..
**Traceback (most recent call last):
Line 18, in <module>
Main()
Line 16, in Main
appnd()
Line 9, in appnd
j=i
UnboundLocalError: local variable 'i' referenced before assignment**
預期結果::下一個序列應該像
5. Line..
6. Line..
7. Line..
請幫助我。
在使用該變量的每個函數中都需要global
定義。
def appnd():
global i
注意:如果可能,請將全局變量和相關函數移到類中。
加
global i
之前
j=i
應該解決問題
您的定義范圍是本地的。 如果您在函數中將變量聲明為全局變量,並不意味着它將應用於所有函數。 您還必須在appnd()函數中將i聲明為全局變量。 話雖如此,這並不意味着您的風格是正確的。 您寧願將變量傳遞給函數。
下一個定義將起作用:
def appnd():
j=i
while i in range(i,j+3):
print "%s .Line..\n" %i
# it would print infinitely, but will work
在編譯時,Python會查看函數中使用變量的方式,以定義查找它們的范圍。 在您對appnd
的定義中,它會看到為i
分配的值,因此試圖將其威脅為局部變量。 在我的代碼中沒有賦值,因此Python只是從父級作用域獲取i
的值-在這種情況下, i
既不是本地的也不是全局的,它稱為free variable 。 執行模型-范圍和綁定 -強烈建議閱讀。
我想您知道何時應該使用全局,否則它將不在您的寫入函數中。 如果僅讀取變量,可以忽略它,我想在您的append函數中需要該變量,但是其中有i + = 1,因此可以對其進行修改。 只需更改追加即可:
for line in range(i, i + 3):
print "%s .Line..\n" % line
在appnd函數中,必須使全局變量i 。
i=1
def wrte():
global i
while i<5:
print "%s .Line..\n" %i
i+=1
def appnd():
global i
j=i
while i in range(i,j+3):
print "%s .Line..\n" %i
i+=1
def Main():
wrte()
appnd()
Main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.