Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在循环中使用局部/全局变量引用/赋值_Python_Loops_Variables_Global_Local - Fatal编程技术网

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)

非常感谢。我将测试哪一个更快。