This means that Python automatically acts like a variable is global unless you define or try to change it in a function. Try adding global a to your code.
>>> a = 123 >>> def f(): ... global a ... print a ... a = 456 ... print a ... >>> f() 123 456 >>> a 456
In the first example, you did not define or modify, so it was global. But if you want, for example, to add 20 to a, you should also use global a .
Also keep in mind that the function a in f is global and its value will differ after the function f is run.
If you want to create a local variable, remember that this declaration always goes before reading, so print a cannot be executed before a = 456 .
EDIT: Good, although we are talking about closures and are dangerous to take advantage of the global opportunity for others.
>>> a = 123 >>> def f(): ... b = a ... print b ... b = 456 ... print b ... >>> f() 123 456 >>> a 123 >>>
Here we use the read-only ability to make a copy and modify this copy without changing the external variable a AS LONG AS IT INTEGER. Remember that b contains a link to a . If a is, for example, a list and operation f similar to b.append(3) , then both a and b will be accessible and changed out of scope.
The choice of method is different due to needs.
Gandi source share