在赋值文本冒险之前引用的局部变量'location'



我正在做一个文本冒险,作为我的第一个python项目。我正在使用一个模板(来自 youtube 教程的应对代码)。但我希望它不创建一个游戏循环,而是一个函数,在玩家输入命令时执行。(该部分正在工作)。以下是本教程中的代码:

Text_Adventure

bridge = ("Bridge", "You are on the bridge of a spaceship, sitting in the captains chair. ")
readyRoom = ("Ready Room" , "The captains ready room ")
lift = ("Lift" , "A turbolift that takes you throughout the ship. ")
transitions = {
    bridge: (readyRoom, lift),
    readyRoom: (bridge,),
    lift: (bridge,)
    }
 
 
location = bridge

while True:
    print (location[1])
    print ("You can go to these places: ")
    for (i, t) in enumerate(transitions[location]):
        print (i + 1, t[0])
    
    choice = int(input('Choose one: '))
    location = transitions[location][choice - 1]

这部分工作正常,但是当我尝试将其转换为函数时:

Text_Adventure

bridge = ("Bridge", "You are on the bridge of a spaceship, sitting in the captains chair. ")
readyRoom = ("Ready Room" , "The captains ready room ")
lift = ("Lift" , "A turbolift that takes you throughout the ship. ")
transitions = {
    bridge: (readyRoom, lift),
    readyRoom: (bridge,),
    lift: (bridge,)
    }
 
 
location = bridge

def travel():
    print (location[1])
    print ("You can go to these places: ")
    for (i, t) in enumerate(transitions[location]):
        print (i + 1, t[0])
    
    choice = int(input('Choose one: '))
    location = transitions[location][choice - 1]
travel()

我收到错误消息:

UnboundLocalError: local variable 'location' referenced before assignment

我知道学习某事的最好方法是自己找到答案。我已经搜索了一段时间,但一无所获,任何帮助将不胜感激,谢谢。

这可以简化很多:

>>> a = 1
>>> def foo():
...    print a
...    a = 3
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'a' referenced before assignment

发生了什么事情

当 python 第一次在函数中看到a时,它是一个非局部变量(在本例中为全局变量)。 第二次,由于你分配给它,python认为它是一个局部变量 - 但是这个名字已经被一个全局变量占用了,这导致了错误。

有一些解决方法 - 您可以将a声明为global,以便python知道当您说a = 3时,您的意思是global变量a是3。 就个人而言,我建议您在代码上多打一些,这样您就不再需要全局变量了。 100 次中有 99 次,如果您使用的是 global,则可能有更好的方法来重构代码,这样您就不需要它了。

如果你写一个全局变量,你应该使用 global 来声明它。取而代之的是:

def travel():

把这个:

def travel():
    global location

感谢您的帮助,我不认为 Ill 会这样保持它,但它现在有效:

#Simplefied version:
a = 1
def foo():
    global a
    a = 3
    print a 
def getFoo():
    print a
print "foo results: "
foo()
print "getFoo results: "
getFoo()

指纹:

foo results: 
3
getFoo results: 
3

我在从另一个函数调用"a"时遇到问题,这就是我分别显示函数和结果的原因。它现在工作,谢谢

最新更新