Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnboundLocalError: local variable 'a' referenced before assignment [duplicate]

Tags:

python

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!

like image 704
Brett7533 Avatar asked Dec 26 '22 04:12

Brett7533


1 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.

like image 122
Ashwini Chaudhary Avatar answered Dec 28 '22 18:12

Ashwini Chaudhary