如果局部变量被引用超出其范围,如何强制Python报错?

How to force Python to report an error if a local variable is referenced out of its scope?

list1 = ["AAA", "BBB"]
for item in list1:
    print(item)

print (item) # <--- out of scope, but Python doesn't report any error

上面的代码,虽然item超出范围,但是Python不会报错

是否可以强制Python报错?

功能范围有限。所以在函数

中保持 for 循环
def f():
  for item in list1:
    print(item)
print(item)

它会抛出错误,但您需要在需要时调用函数。

循环中使用的变量最终会到达可迭代对象的索引“-1”。因此,每次您使用 上一个循环 中使用的 相同变量 时,它将 return list1[-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会加注