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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章