函数不改变全局变量 [英] Function Not Changing Global Variable

查看:116
本文介绍了函数不改变全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

my code is as follow:

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()

由于某些原因,当我的代码输入if语句时,在函数完成后,不会退出while循环。

For some reason when my code enters the if statement, it doesn't exit the while loop after it's done with function().

但是,如果我这样编码:

BUT, if I code it like this:

done = False

while done == False:
    for loop:
    code
    if not comply:
        done = True  #let's say that the code enters this if-statement

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

...it exits the while loop. What's going on here?

我确定我的代码输入了if语句。我还没有运行调试器,因为我的代码有很多循环(相当大的二维数组),我放弃了调试,因为它非常繁琐。在函数中,完成怎么没有被改变?

I made sure that my code enters the if-statement. I haven't run the debugger yet because my code has a lot of loops (pretty big 2D array) and I gave up on debugging due to it being so tedious. How come "done" isn't being changed when it's in a function?

推荐答案

你的问题是函数创建自己的名称空间,这意味着该函数中的 done 与第二个示例中的 done 不同。使用全局完成来使用第一个 done ,而不是创建一个新的。

Your issue is that functions create their own namespace, which means that done within the function is a different one than done in the second example. Use global done to use the first done instead of creating a new one.

def function():
    global done
    for loop:
        code
        if not comply:
            done = True

解释如何使用 global 可以找到此处

An explanation of how to use global can be found here

这篇关于函数不改变全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆