Python (3)列表有一些问题。
def initLocations():
locName = ["The Town","The Blacksmith Hut"]
locDesc = ["A small but beautiful town. You've lived here all your life.", "There are many shops here, but the Blacksmith Hut is the most intricate."]这是脚本的顶部。稍后,它将由以下名称调用:
initLocations()然后大约4行之后:
while currentLoc<20:
initLocations()
print("Type 'Help' for advice on what to do next.")
passedCommand = input("?: ")
mainProcess(passedCommand)更多信息在这里:http://pastebin.com/5ib6CJ4g
继续得到错误
print("Left: " + locName[currentLoc-1])
NameError: name 'locName' is not defined任何帮助都很感激。
发布于 2015-01-25 14:13:46
函数中定义的变量是该函数的本地变量。它们不会泄漏到调用范围(这是一件好事)。如果您想要函数提供可用的东西,则需要返回它们。例如:
def initLocations():
locName = […]
locDesc = […]
return locName, locDesc这将使函数返回一个包含名称列表和描述列表的二元组。在调用函数时,您将需要捕获这些值并再次将它们保存到变量中。例如:
locName, locDesc = initLocations()发布于 2015-01-25 14:13:12
仅仅调用一个函数并不会在外部范围内创建变量。您将不得不使他们global,但这是一个非常糟糕的方式做一些事情。您需要从函数中return它。在initLocations()中,您需要有一个语句return locName,当您调用它时,您需要使用locName = initLocations()。如果您有两个变量,则需要将它们作为元组发送。
演示
def initLocations():
locName = ["The Town","The Blacksmith Hut"]
locDesc = ["A small but beautiful town. You've lived here all your life.", "There are many shops here, but the Blacksmith Hut is the most intricate."
return (locName,locDesc)然后
while currentLoc<20:
locName,locDesc = initLocations()
print("Type 'Help' for advice on what to do next.")
passedCommand = input("?: ")
mainProcess(passedCommand)这被称为元组包装序列解压。
小票
正如Padraic在comment中提到的,拥有一个函数来声明这两个列表是非常无用的(除非你必须这样做)。
你可以这样做,
locName = ["The Town","The Blacksmith Hut"]
locDesc = ["A small but beautiful town. You've lived here all your life.", "There are many shops here, but the Blacksmith Hut is the most intricate."
while currentLoc<20:
print("Type 'Help' for advice on what to do next.")
passedCommand = input("?: ")
mainProcess(passedCommand)这是一个更好的方法
发布于 2015-01-25 14:15:14
initLocations内部的作用域不是全局的。除非变量声明为global或函数作为值返回,否则在该函数的作用域外部(包含范围级别)中将无法使用在该函数范围内创建的值。
第二种办法非常可取:
def initLocations():
locName = ["The Town","The Blacksmith Hut"]
locDesc = ["A small but beautiful town. You've lived here all your life.",
"There are many shops here, but the Blacksmith Hut is the most intricate."]
return locName, locDesc然后,在稍后调用该函数时:
locName, locDesc = initLocations()https://stackoverflow.com/questions/28137283
复制相似问题