I am new to Python, and here's a question that is really confusing me:
i = 1
def foo():
while i < 5:
print 'in while loop'
i += 1
foo()
This code produces an error:
UnboundLocalError: local variable 'i' referenced before assignment
Why isn't the while loop seeing the global i ? As explained in the LEGB-rule, Python will search for the variable name sequentially until eventually searches in the global scope ?!
Why do I have to explicitly refer that i is global by adding global keyword:
i = 1
def foo():
global i
while i < 5:
print 'in while loop'
i += 1
On the other hand here foo prints the global value for i, '1' without adding global keyword.
i = 1
def foo():
print 'i equals %d' % i