已经看过其他答案,似乎无法解决这个问题。
这是我的完整代码: http : //pastebin.com/tW1kntG3
有问题的代码在这里:
#Define the variables global currentLoc currentLoc=0(显然,破坏代码的部分是第37行。)
if call=="move": print("Move where?") print("") if currentLoc==0: print("Left: You cannot move left.") print("Right: " + locName[currentLoc+1]) elif currentLoc>1: print("Left: " + locName[currentLoc-1]) print("Right: " + locName[currentLoc+1]) print("") print("Move left or right? Enter your choice.") direction = input("?: ") if direction=="left": print("Moved left.") if currentLoc>1: currentLoc = currentLoc-1 pass elif direction=="right": currentLoc = currentLoc+1 pass pass我的错误:
if currentLoc==0: UnboundLocalError: local variable 'currentLoc' referenced before assignmentalready looked at other answers and can't seem to fix this.
Here's my full code: http://pastebin.com/tW1kntG3
The code in question lies around here:
#Define the variables global currentLoc currentLoc=0(The part that is breaking the code, apparently, is line 37.)
if call=="move": print("Move where?") print("") if currentLoc==0: print("Left: You cannot move left.") print("Right: " + locName[currentLoc+1]) elif currentLoc>1: print("Left: " + locName[currentLoc-1]) print("Right: " + locName[currentLoc+1]) print("") print("Move left or right? Enter your choice.") direction = input("?: ") if direction=="left": print("Moved left.") if currentLoc>1: currentLoc = currentLoc-1 pass elif direction=="right": currentLoc = currentLoc+1 pass passMy error:
if currentLoc==0: UnboundLocalError: local variable 'currentLoc' referenced before assignment最满意答案
您需要在函数中声明全局。 Python确定每个范围的名称范围 。 如果您在函数中指定名称(或将其用作导入目标,或for目标或参数等),则除非另有说明,否则Python会将该名称设置为本地名称。
因此,在全球范围内使用global是毫无意义的,因为Python已经知道它是全局的。
将global语句添加到尝试更改名称的每个函数中:
def displayMessage(call): global currentLocYou need to declare a global in the function. Python determines name scope per scope. If you assign to a name in a function (or use it as an import target, or a for target, or an argument, etc.) then Python makes that name a local unless stated otherwise.
As such, using global at the global level is rather pointless, because Python already knows it is a global there.
Add your global statement into each of function that tries to alter the name:
def displayMessage(call): global currentLoc更多推荐
发布评论