功能不改变全局变量

cYn*_*cYn 34 python global-variables

我的代码如下:

done = False

def function():
    for loop:
        code
        if not comply:
            done = True  #let's say that the code enters this if-statement

while done == False:
    function()
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我的代码进入if语句时,它在使用function()完​​成后不会退出while循环.

但是,如果我这样编码:

done = False

while done == False:
    for loop:
    code
    if not comply:
        done = True  #let's say that the code enters this if-statement
Run Code Online (Sandbox Code Playgroud)

...它退出while循环.这里发生了什么?

我确保我的代码输入if语句.我还没有运行调试器因为我的代码有很多循环(非常大的2D数组)而且我放弃了调试,因为它太繁琐了.为什么"完成"在功能中没有被改变?

Sna*_*fee 47

您的问题是函数创建自己的命名空间,这意味着done函数内部done与第二个示例不同.使用global done使用第一done,而不是创建一个新的.

def function():
    global done
    for loop:
        code
        if not comply:
            done = True
Run Code Online (Sandbox Code Playgroud)

global可在此处找到有关如何使用的说明


Ion*_*lub 6

done=False
def function():
    global done
    for loop:
        code
        if not comply:
            done = True
Run Code Online (Sandbox Code Playgroud)

您需要使用global关键字让解释器知道您引用了global变量done,否则它将创建另一种只能在函数中读取的变量。


Ash*_*ary 5

使用global,只有这样,您才能修改全局变量,否则done = True函数内部的语句将声明一个名为的新局部变量done

done = False
def function():
    global done
    for loop:
        code
        if not comply:
            done = True
Run Code Online (Sandbox Code Playgroud)

阅读有关全局声明的更多信息。