Python function not changing variable
my code is as follow: Show
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:
...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?
codeforester 35.6k15 gold badges99 silver badges125 bronze badges asked Sep 30, 2012 at 23:21
1 Your issue is that functions create their own namespace, which means that
An explanation of how to use
answered Sep 30, 2012 at 23:23
you need to use the
global keyword to let the interpreter know that you refer to the global variable
Tim 40.3k18 gold badges126 silver badges142 bronze badges answered Sep 30, 2012 at 23:23
Ionut HulubIonut Hulub 5,9275 gold badges26 silver badges53 bronze badges Use
Read more about the global statement. answered Sep 30, 2012 at 23:23
Ashwini ChaudharyAshwini Chaudhary 236k55 gold badges443 silver badges495 bronze badges Using a class rather than global:Another way to handle (not use) global variables is to wrap the functions and variables you wish to be global in a class. While this is a little heavy for this specific case - classes add a host of functionality and flexability to the project. (Personally) highly recommended. For example:
Output:
answered Jan 21, 2020 at 9:35
S3DEVS3DEV 7,6753 gold badges27 silver badges36 bronze badges How do you change a variable in a function Python?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 Python functions change global variables?A print statement inside the function should print the updated value of x . In python, a function can only access and print a global variable . We need to tell the function referring for any assignment or change to the global variable .
Can a function update a global variable?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 you overwrite variables in Python?Python Variables. Assignment like x = 10 above sets a pointer into that variable, pointing to the value.. Assignment like y = 'bye' above, where the variable has an existing pointer in it, overwrites the existing pointer with the new one.. |