1

作为我的第一个 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

我知道学习东西的最好方法是自己找到答案。我一直在寻找一段时间,但没有得到任何地方,任何帮助将不胜感激,谢谢。

4

3 回答 3

1

这可以简化很多:

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

发生了什么

当pythona在函数中第一次看到时,它是一个非局部变量(在这种情况下是一个全局变量)。但是第二次,由于您正在分配它,python 认为它是一个局部变量——但是该名称已经被一个全局变量占用,这会导致错误。

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

于 2013-10-26T02:37:44.907 回答
0

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

def travel():

把这个:

def travel():
    global location
于 2013-10-26T02:36:29.497 回答
0

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

#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”时遇到了麻烦,这就是我分别显示函数和结果的原因。它现在工作,谢谢

于 2013-10-28T23:20:31.197 回答