坚持使用 Python 3 列表

Stuck using Python 3 List

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

感谢任何帮助。

仅仅调用函数不会在外部作用域中创建变量。您将不得不制作它们 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 在 中提到的 只声明 2 个列表的函数是没有用的(除非你必须这样做)

您可以改为这样做,

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)

哪种方法更好

函数内定义的变量是该函数的局部变量。它们不会泄漏到调用范围(这是一件好事)。如果你想让函数使东西可用,你需要 return 它们。例如:

def initLocations():
    locName = […]
    locDesc = […]
    return locName, locDesc

这将使函数 return 成为包含名称列表和描述列表的二元组。调用该函数时,您需要捕获这些值并将它们再次保存到变量中。例如:

locName, locDesc = initLocations()

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