Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 892
cYn Avatar asked Sep 30 '12 23:09

cYn


People also ask

Can function change global variables?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).

How do I change global values in a function?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

Can global variables be changed in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

How can you force a variable in a function to refer to the global variable?

If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.


2 Answers

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

like image 54
Snakes and Coffee Avatar answered Oct 16 '22 20:10

Snakes and Coffee


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

you need to use the global keyword to let the interpreter know that you refer to the global variable done, otherwise it's going to create a different one who can only be read in the function.

like image 29
Ionut Hulub Avatar answered Oct 16 '22 18:10

Ionut Hulub