坚持使用Python 3 List

时间:2015-01-25 14:07:42

标签: python 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

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:2)

函数中定义的变量是该函数的本地变量。它们不会泄漏到调用范围内(这是一件好事)。如果您希望函数使事物可用,则需要返回它们。例如:

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

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

locName, locDesc = initLocations()

答案 1 :(得分:1)

仅调用函数不会在外部作用域中创建变量。你必须让他们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中提到的那样 有一个函数来声明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)

哪种方式更好

答案 2 :(得分:0)

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