Python:在循环中使用局部/全局变量引用/赋值
我有以下循环结构,还有一个问题,就是由于Python:在循环中使用局部/全局变量引用/赋值,python,loops,variables,global,local,Python,Loops,Variables,Global,Local,我有以下循环结构,还有一个问题,就是由于UnboundLocalError,无法在该代码中增加变量: while True: def function_1(): def function_2(): x += 1 print(x) function_2() function_1() 我现在的解决方案是: x = 0 while True: def function_1(): d
UnboundLocalError
,无法在该代码中增加变量:
while True:
def function_1():
def function_2():
x += 1
print(x)
function_2()
function_1()
我现在的解决方案是:
x = 0
while True:
def function_1():
def function_2():
global x
x += 1
print(x)
function_2()
function_1()
是否有其他不带全局的解决方案?使用可变值
x = []
x.append(0)
while True:
def function_1():
def function_2():
x[0]= x[0]+1
print x[0]
function_2()
function_1()
向所有函数传递并返回x
x = 0
while True:
def function_1(x1):
def function_2(x2):
x2 += 1
print(x2)
return x2
return function_2(x1)
x = function_1(x)
非常感谢。我将测试哪一个更快。