0
count = 0

def test():
    number = 3
    while count < 6:
        count = number + 3

test()

The above code generates the following error.

UnboundLocalError: local variable 'count' referenced before assignment

count = 0

def test():
    number = 3
    while count < 6:
        print(count)
        break

test()

But the code above runs well.

What is the difference between the two codes?

newbieeyo
  • 663
  • 4
  • 12
  • The difference is that the first one assigns the variable in the function, which makes it a local variable. The second one only reads the variable, so it uses the global variable. – Barmar Jul 23 '20 at 05:24
  • you need ```def test(count)``` and you need then to ```test(count)``` – Roan Jul 23 '20 at 05:27
  • Or if you intend to modify the global variable (which is not good style - you should generally avoid globals for all osrts of reasons), add `global count` in the function. – DisappointedByUnaccountableMod Jul 23 '20 at 06:11

0 Answers0