UnboundLocalError: local variable x referenced before assignment

(一):多数情况

a = 1
def test():
    a += 1
test()

在这里插入图片描述
解决办法:
(1):将全局变量作为参数传入

a = 1
def test(a):
    a += 1
    print(a)
test(a)

(2):在方法中定义局部变量

a = 1
def test():
    a = 1
    a += 1
    print(a)
test()

(3):使用global关键字

a = 1
def test():
    global a
    a += 1
    print(a)
test()
print(a)

(4):使局部变量与全局变量不重名

a = 1
def test():
    b = a + 1
    print(b)
test()

(二):少数情况

def test1():
    return 1
def test2():
    test1 = test1()
test2()

在这里插入图片描述
解决办法:

def test1():
    return 1
def test2():
    test3 = test1()
    print(test3)
test2()

猜你喜欢

转载自blog.csdn.net/yeyu_xing/article/details/106201197