list1 = ["AAA", "BBB"]
for item in list1:
print(item)
print (item) # <--- out of scope, but Python doesn't report any error
对于上面的代码,虽然item
超出了它的范围,但是Python不会报错。
是否可以强制 Python 报告错误?
在循环中使用的变量最终将到达可迭代对象的索引“-1”。所以每次使用该时间相同的变量在使用之前的循环,它会返回列表1 [-1]这确实是Python中的每个迭代对象的最后一个元素
解决方案:您可以使用del
关键字删除该变量
list1 = ["AAA", "BBB"]
for item in list1:
print(item)
del item #now item is not a defined variable in our program.
print (item) #<--- will throw an error because the variable "item" no longer exists
NameError
将被提出
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句