这是代码:
aList = []
for p in anotherList:
aList.append(p)
try:
k=p.someMethod()
aList.append(k) #getting error here
except someException:
continue
return aList
我收到“全局名称错误--aList 未定义。为什么会这样?
如果aList
未定义,您应该在进入 try-except 子句aList.append(p)
之前在循环顶部收到错误。aList.append(k)
你确定你没有错别字?
aList = []
for p in anotherList:
aList.append(p) # <== should have gotten error here first!
try:
k=p.someMethod()
aList.append(k) #getting error here
except someException:
continue
return aList
这段代码没有任何问题。
>>> anotherList = [1, 2, 3, 4, 5]
>>> aList = []
>>> for p in anotherList:
... aList.append(p)
... try:
... aList.append(9)
... except someException:
... continue
...
>>> aList
[1, 9, 2, 9, 3, 9, 4, 9, 5, 9]
如您所见,它有效。
如果您仍然有问题,请发布更多代码,您发布的部分没有错误。