UnboundLocalError: local variable 'a' referenced before assignment

Question:

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!

Asked By: Brett7533

||

Answers:

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.

Answered By: Ashwini Chaudhary
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.