Python:在循环中使用本地/全局变量引用/赋值

时间:2017-02-22 07:21:38

标签: 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():
        def function_2():
            global x
            x += 1
            print(x)
        function_2()
    function_1()

是否有其他解决方案没有global

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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)
相关问题