I'm working on something in python where I need to use a global variable that is changed by a function. However, when I try to change the value inside the function, python instead creates a new local variable instead of accessing the global one.
For example, if I had the following useless function, it would give an error of "local variable 'x' referenced before assignment"
x=5
def example():
#This would of course normally use += but that's not applicable to my actual code
x=x+5
Is there a way to tell python I want to access the existing variable rather than create a new one? I know I could pass it as a parameter but this is much more intuitive with how the code is structured
global xstatement inside the function, as otherwise the fact that the function assigns to the variable would make it a local.globalin this case, actually you probably don't want to do that (global variables are evil!). In most cases if you need to access a variable inside a function, the best way is to pass that variable as a parameter. Another option is encapsulate the function inside a class. Then you can make the variablexan attribute of the class and you can access it inside the method example doingself.x. So in short: You can solve what you want to do using global, but you probably should not do it.