【问题标题】:Can't find the reason for the error in my code in python在我的python代码中找不到错误的原因
【发布时间】:2014-08-28 20:13:48
【问题描述】:

我是 Python 初学者,正在通过 Learn Python the Hard Way 进行学习。

很遗憾,我不断收到错误消息,不知道为什么。

代码如下:

def new(num_buckets=256): # Creates list aMap and fills it with 256 empty lists.
    """ Initializes a Map with the given number of buckets."""
    aMap = []
    for i in range(0, num_buckets):
        aMap.append([])
    return aMap

new()
print aMap

奇怪的是,我不断收到一条消息,说 aMap 未定义,即使我只是运行了一个函数,将它创建为列表中的一堆空桶。

感谢您的帮助。

【问题讨论】:

  • er.. 但aMap 不是仅在您的new 函数中定义并因此作用域吗?你想做print(new())吗?或temp = new() print(temp)?
  • 我想你不太明白return 的作用,以及变量的作用域。
  • 您需要处理返回变量。你可以做 result = new() 然后做 print result;
  • 谢谢大家。我还没有了解全局变量。现在我明白了,这似乎有点愚蠢。

标签: python hashmap


【解决方案1】:

new() 返回 aMap,但你永远不会将它存储在任何地方。你想要:

aMap = new()

一般来说,除非您明确声明(通过globalnonlocal1 语句),否则名称仅存在于定义它的范围内。在这种情况下,名称aMap 仅存在于函数new 中。要使该名称存在于函数之外,您需要为其分配一些内容。

1仅限 Python3.x

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多