2017-07-18 61 views
-2

在「count + = 1」時拋出錯誤。我試圖讓它成爲一個全球性的,它仍然給了一個問題。這不過是一個笑話而已,但我想知道它爲什麼不起作用。UnboundLocalError:分配前引用的本地變量'count'

import math 
def delT(): 
    #inputs 
    #float inputs 
    #do math 
    #print results 
    global count 
    count=0 
    def getAndValidateNext(): 
     #print menu 
     getNext=input("select something") 
     acceptNext=["things","that","work"] 
     while getNext not in acceptNext: 
      count+=1 
      print("Not a listed option.") 
      if count==5: 
       print("get good.") 
       return 
      return(getAndVadlidateNext()) 
     if getNext in nextRestart: 
      print() 
      return(delT()) 
     if getNext in nextExit: 
      return 
    getAndVadlidateNext() 
delT() 
+0

請完整追溯。如果我的眼睛看不到,該功能不會被調用... –

+0

什麼是'getAndVadlidateNext'? – user2357112

+1

[Python嵌套函數變量作用域]的可能重複(https://stackoverflow.com/questions/5218895/python-nested-functions-variable-scoping) – janos

回答

1

您需要向下移動你的global關鍵字插入功能。

count=0 
def getAndValidateInput(): 
    global count 
    #print menu 
    #So on and so forth 

現在你應該可以訪問你的count變量。它與Python中的範圍確定有關。你必須聲明一個變量在每個函數中都是全局的,而不僅僅是它定義的地方。

+0

啊嗯。我剛添加它,它正常工作。必須在getAndValidateNext中聲明它爲全局,並將其定義爲0.解決,謝謝! – pythonOnlyPls

0

我遇到了同樣的問題一次,事實證明,這與範圍有關,並且在另一個函數定義中有一個函數定義。有效的是編寫獨立的函數來創建和修改全局變量。像這樣的例子:

def setcount(x): 
    global count 
    count = x 
def upcount(): 
    global count 
    count += 1 
1

global count應該在getAndValidateInput()函數裏面。

相關問題