Skip to main content
 首页 » 编程设计

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

2024年10月01日7grandyang

我有以下循环结构和问题,由于 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的解决方案?

请您参考如下方法:

使用可变值。

x = [] 
x.append(0) 
while True: 
    def function_1(): 
        def function_2(): 
            x[0]= x[0]+1 
            print x[0] 
        function_2() 
    function_1()