Python 3: "Local Variable referenced before assignment"
Python 3: "Local Variable referenced before assignment"
已经看过其他答案,但似乎无法解决这个问题。
这是我的完整代码: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 assignment
您需要在函数中声明一个全局。 Python 确定名称范围 每个范围 。如果您在函数中分配一个名称(或将其用作导入目标、for
目标或参数等),则 Python 会使该名称成为局部名称,除非另有说明。
因此,在全局级别使用 global
是毫无意义的,因为 Python 已经知道它在那里是全局的。
将您的 global
语句添加到每个试图更改名称的函数中:
def displayMessage(call):
global currentLoc
global
关键字在函数范围内引入了一个全局变量,它并没有将其声明为整个程序的全局变量。您必须在要访问 var_name
变量的函数中使用 global var_name
。
已经看过其他答案,但似乎无法解决这个问题。
这是我的完整代码: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 assignment
您需要在函数中声明一个全局。 Python 确定名称范围 每个范围 。如果您在函数中分配一个名称(或将其用作导入目标、for
目标或参数等),则 Python 会使该名称成为局部名称,除非另有说明。
因此,在全局级别使用 global
是毫无意义的,因为 Python 已经知道它在那里是全局的。
将您的 global
语句添加到每个试图更改名称的函数中:
def displayMessage(call):
global currentLoc
global
关键字在函数范围内引入了一个全局变量,它并没有将其声明为整个程序的全局变量。您必须在要访问 var_name
变量的函数中使用 global var_name
。