2
a = 4
def foo(x):
    a = 10
foo(2)
print(a)
#prints 4

The code above doesn't change a

a = 4
def foo(x):
   return a + x
result = foo(10)
print(result)
#prints out 14

I don't quite understand how these two act differently. The second one, the global variable obviously affects the local variable in foo. But if I change a in the first one inside the foo, nothing happens to a in the global frame. What is happening?

chanpkr
  • 895
  • 2
  • 10
  • 21
  • 1
    It's helpful to know that Python looks up variable names using something called the [LEGB scoping rule](http://stackoverflow.com/a/292502/355230). The result of that search also determines which ones it considers to be local when they're encountered. – martineau Sep 18 '13 at 22:14

2 Answers2

4

If you want to change a global variable inside the function, you should use global keyword:

a = 4
def foo(x):
    global a
    a = 10
foo(2)
print(a)  # prints 10

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    In fact, it's _always_ safe to use `global` to access a global variable, even if you're not assigning to it, or not sure, or can't remember the rule. And in many cases, it makes your code clearer, too. – abarnert Sep 18 '13 at 22:51
3

What is happening?

In the first case, you have two different variable named a: One (a = 10) is part of the function's scope and can only be accessed from inside the function. This variable is deleted after the function returns. The other variable (a = 4) is part of the outer (global) scope and is not affected in any way.

In the second snippet, there is only one variable a. This variable is in the global scope, but it can also be accessed (read) from inside the function. It can't be changed from inside the function, though.

flornquake
  • 3,156
  • 1
  • 21
  • 32