UnboundLocalError:赋值前引用的局部变量“a”[duplicate]

时间:2022-01-05 03:50:55

This question already has an answer here:

这个问题已经有了答案:

if execute the following code will show error message:

如果执行下列代码将显示错误消息:

UnboundLocalError: local variable 'a' referenced before assignment

UnboundLocalError:在赋值之前引用的本地变量“a”

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!

它会很好。任何建议或建议都会很棒。谢谢!

1 个解决方案

#1


9  

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.

当python看到像a = a + 1这样的赋值语句时,它会认为变量a是局部变量,当函数被称为表达式c > a/b时,会引起错误,因为a还没有定义。

#1


9  

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.

当python看到像a = a + 1这样的赋值语句时,它会认为变量a是局部变量,当函数被称为表达式c > a/b时,会引起错误,因为a还没有定义。