UnboundLocalError:在赋值前引用'count'局部变量



在"count+=1"处抛出错误。我尝试将其设为全球等,但它仍然存在问题。这更像是一个笑话,但我想知道为什么它不起作用。

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()

您需要将global关键字向下移动到函数中。

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

现在您应该能够访问您的计数变量。它与 Python 中的范围界定有关。您必须在要使用它的每个函数中声明一个变量是全局的,而不仅仅是定义它的位置。

我曾经遇到过同样的问题,结果证明这与范围有关,并且在另一个函数定义中有一个函数定义。有效的方法是编写单独的函数来创建和修改全局变量。例如,像这样:

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

global count应该在getAndValidateInput()函数内。

最新更新