我正在进行文本冒险,这是我的第一个python项目。我正在使用模板,(来自youtube教程的应对代码)。但是我没有创建一个游戏循环,而是希望它成为一个函数,在玩家输入命令时执行。 (那部分正在运作)。 以下是教程中的代码:
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]
那部分工作正常,但是当我试图把它变成一个函数时:
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
我知道学习的最好方法是亲自找到答案。我一直在寻找一段时间而且没有到达任何地方,非常感谢任何帮助,谢谢。
答案 0 :(得分: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
当python第一次在函数中看到a
时,它是一个非局部变量(在本例中是全局变量)。第二次,因为你分配给它,python认为它是一个局部变量 - 但是这个名字已经被一个导致错误的全局变量所取代。
有一些解决方法 - 您可以将a
声明为global
,以便python知道当您说a = 3
时,您的意思是global
变量{ {1}}是3.就个人而言,我建议你更多地使用代码,以便不再需要全局变量。如果您使用a
,则有100次中的99次,可能有更好的方法来重构代码,因此您不需要它。
答案 1 :(得分:0)
如果您写入全局变量,则应使用global
来声明它。
而是这个:
def travel():
把这个:
def travel():
global location
答案 2 :(得分: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”,这就是我分别显示函数和结果的原因。它现在正在工作,谢谢你