Python:不重新分配变量

Ran*_*bia 1 python variables function

当调用tst时,为什么下面的变量(A,B,C,D)没有改变.

A,B,C = 0,0,0
D = 0

def tst():
    A,B,C = 1,2,3
    D = 4
    print(A,B,C,D)

tst() # tst is called
print(A,B,C,D)

Output:

(1, 2, 3, 4)
(0, 0, 0, 0)
Run Code Online (Sandbox Code Playgroud)

Mik*_*ran 6

因为Python的范围规则.

在def tst()中,您将创建局部变量A,B和C,并为它们分配新值.

如果要分配全局A,B和C值,请使用global关键字.