Given the following code:
U = [1,2,3]
def test():
# global U
u = U * 2
print(u)
# U = u
test()
print(U)
In this form prints(u) displays [1,2,3,1,2,3]. This means 'U' was read successfully in the function.
But if I uncomment the U = u line then I receive the following error message:
u = U * 2 UnboundLocalError: local variable 'U' referenced before assignment
which I can only fix by uncommenting the 'global U' line. I dont understand this though. Previously u=U*2 worked just fine. Why is an error raised at u=U*2 if I uncomment a line below it?
EDIT: I dont think it is duplicate. My question is why do I see an error in a line which is unmodified. In my real code there are about 100 lines between 'u=U*2' and 'U=u' and it took me couple hours ro realize that the error is actually somehow caused by the 'U=u' line.