2017-07-18 53 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()函数里面。

相关问题