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

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

For the code above, although item is out of its scope, Python will not report an error.

Is it possible to force Python to report an error?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
camino
  • 10,085
  • 20
  • 64
  • 115

2 Answers2

0

the variable that's being used in a loop will eventually arrive at the index "-1" of an iterable object. So each time you use that same variable used in a previous loop, it will return list1[-1] which is indeed the last element in every iterable object in python

Solution: you can use del keyword to delete that variable

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 will be raised

Maamoun
  • 81
  • 5
-1

Functions have limited scope. So keep for loop inside function

def f():
  for item in list1:
    print(item)
print(item)

It will throw an error but you need to call a function whenever it required.

Zalak Bhalani
  • 979
  • 7
  • 15