-1

The below function works fine:

def ex():
    for x in a:
        print(x)   
a=[200]
ex()

But the below throws a "UnboundLocalError: local variable 'a' referenced before assignment" error

def ex():
    for x in a:
        print(x)   
    a=0
a=[200]
ex()

Why is this happening?

codingsplash
  • 4,785
  • 12
  • 51
  • 90

1 Answers1

0

In your first example, the a refers to the global variable a. In the second, python interprets your line a=0 and because of this, it thinks that you mean the local variable. To fix the error, you can give a as a second param or write global a as the first line of the function

Maettel
  • 46
  • 6