4

if execute the following code will show error message:

UnboundLocalError: local variable 'a' referenced before assignment

a = 220.0
b = 4300.0
c = 230.0/4300.0

def fun():
    while (c > a/b):
        a = a + 1
        print a/b

if __name__ == '__main__':
    fun()

but modify to :

a = 220.0
b = 4300.0
c = 230.0/4300.0

def fun():
    aa = a
    bb = b
    while (c > aa/bb):
        aa = aa + 1
        print aa/bb

if __name__ == '__main__':
    fun()

it will fine. Any advice or pointers would be awesome. Thanks a lot!

Brett7533
  • 342
  • 1
  • 3
  • 12

1 Answers1

10

You can't modify a global variable without using the global statement:

def fun():
    global a 
    while (c > a/b):
        a = a + 1
        print a/b

As soon as python sees an assignment statement like a = a + 1 it thinks that the variable a is local variable and when the function is called the expression c > a/b is going to raise error because a is not defined yet.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504