【发布时间】: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;
-
谢谢大家。我还没有了解全局变量。现在我明白了,这似乎有点愚蠢。