在python中,我一直收到一个未绑定的本地错误,代码如下:
xml=[]
global currentTok
currentTok=0
def demand(s):
if tokenObjects[currentTok+1].category==s:
currentTok+=1
return tokenObjects[currentTok]
else:
raise Exception("Incorrect type")
def compileExpression():
xml.append("<expression>")
xml.append(compileTerm(currentTok))
print currentTok
while currentTok<len(tokenObjects) and tokenObjects[currentTok].symbol in op:
xml.append(tokenObjects[currentTok].printTok())
currentTok+=1
print currentTok
xml.append(compileTerm(currentTok))
xml.append("</expression>")
def compileTerm():
string="<term>"
category=tokenObjects[currentTok].category
if category=="integerConstant" or category=="stringConstant" or category=="identifier":
string+=tokenObjects[currentTok].printTok()
currentTok+=1
string+="</term>"
return string
compileExpression()
print xml
以下是我得到的确切错误:
^{pr2}$这对我来说毫无意义,因为我清楚地将currentTok
初始化为我代码的第一行,我甚至将其标记为global
,只是为了安全起见,并确保它在我所有方法的作用域内。在
您需要将
global currentTok
行放入函数中,而不是主模块中。在global
关键字告诉函数它需要在全局范围内查找该变量。在您需要在函数定义中声明它是全局的,而不是在全局范围内。在
否则,Python解释器会看到它在函数中被使用,假设它是一个局部变量,然后在第一件事是引用它而不是赋值给它时发出抱怨。在
相关问题 更多 >
编程相关推荐