Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a global variable from within a function?

I'm trying to add or subtract from a defined variable, but I can't figure out how to overwrite the old value with the new one.

a = 15  def test():     a = a +10     print ( a )  test() 

Error message:

Traceback (most recent call last):   File "test.py", line 7, in <module>     test()   File "test.py", line 4, in test     a = a +10 UnboundLocalError: local variable 'a' referenced before assignment 
like image 559
user7351337 Avatar asked Dec 28 '16 20:12

user7351337


People also ask

How do I change a global variable inside 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.

How do you change the value of a global variable within a function Python?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword. E.g. This would change the value of the global variable to 55.

Can the value of global variable be changed?

Any statement written in the program can change the value of the global variable. This may give unpredictable results in multi-tasking environments. If global variables are discontinued due to code refactoring, you will need to change all the modules where they are called.


1 Answers

The error that you get when you try to run your code is:

UnboundLocalError: local variable 'a' referenced before assignment 

… which, on the face of it, seems strange: after all, the first statement in the code above (a = 15) is an assignment. So, what's going on?

Actually, there are two distinct things happening, and neither of them are obvious unless you already know about them.

First of all, you actually have two different variables:

  • The a in your first line is a global variable (so called because it exists in the global scope, outside of any function definitions).

  • The a in the other lines is a local variable, meaning that it only exists inside your test() function.

These two variables are completely unrelated to each other, even though they have the same name.

A variable is local to a function if there's a statement assigning to it inside that function - for instance, your a = a +10 line.

Even so, the error still looks strange - after all, the very first thing you do inside test() is assign to a, so how can it be referenced beforehand?

The answer is that, in an assignment statement, Python evaluates everything on the right hand side of the = sign before assigning it to the name on the left hand side – so even though the assignment is written first in your code, a gets referenced first in that right hand side: a +10.

There are two ways you can get around this. The first is to tell Python that you really want the a inside test() to be the same a in the global scope:

def test():     global a     a = a + 10     print(a) 

This will work, but it's a pretty bad way to write programs. Altering global variables inside functions gets hard to manage really quickly, because you usually have lots of functions, and none of them can ever be sure that another one isn't messing with the global variable in some way they aren't expecting.

A better way is to pass variables as arguments to functions, like this:

a = 15  def test(x):     x = x + 10     print(x)  test(a) 

Notice that the name doesn't have to be the same - your new definition of test() just says that it accepts a value, and then does something with it. You can pass in anything you like – it could be a, or the number 7, or something else. In fact, your code will always be easier to understand if you try to avoid having variables with the same name in different scopes.

If you play with the code above, you'll notice something interesting:

>>> a = 15 >>> test(a) 25 >>> a 15 

a didn't change! That's because although you passed it into test() and it got assigned to x, it was then x that got changed, leaving the original a alone.

If you want to actually change a, you need to return your modified x from the function, and then reassign it back to a on the outside:

>>> a = 15 >>>  >>> def test(x): ...     x = x + 10 ...     print(x) ...     return x ...  >>> a = test(a) 25 >>> a 25 
like image 50
Zero Piraeus Avatar answered Sep 28 '22 00:09

Zero Piraeus