代码不向"ctr"变量添加一个。怎么做?
ctr = 0
def x(ctr): #function A
ctr+=1
def y(): #function B
global ctr
x(ctr) #function A
y()
print(ctr)
>>> 0
整数是通过值传递的,而不是通过引用传递的。您必须在x()
中global ctr
才能修改全局变量,或者返回分配给值的结果:
ctr = 0
def x(ctr): #function A
ctr+=1
return ctr
def y(): #function B
global ctr
ctr = x(ctr) #function A
y()
print(ctr)