Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - Function not changing global variable

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

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 exits the while loop. What's going on here?

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?

question from:https://stackoverflow.com/questions/12665994/function-not-changing-global-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

An explanation of how to use global can be found here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...