-1

Given the following:

a = 0
def func():
    a += 2
    print(a)
func()
print(a)

I get a UnboundLocalError: local variable 'a' referenced before assignment error. Fair enough, since a is local to func.

However when remove the increment statement and simply want to just print a within func, it works.

a = 0
def func():
    print(a)
func()
print(a)

Why does it work then? Why does the increment operator not see a while the print statement does?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
doofus
  • 124
  • 1
  • 5

2 Answers2

0

In order to modify a global variable in Python, it needs the global keyword.

For instance, try:

a = 0
def func():
    global a
    a += 2
    print(a)

However, when we simply want to read a global value (as is the case where we are printing it out), we don't need the global keyword.

  • Yes, that's what I was thinking too. But that's weird. Why would the scope of a variable vary depending on whether we want to read or modify it? I think it should be either in scope or not in scope, regardless of the operation we want to perform. – doofus Jan 16 '23 at 01:49
  • @adrianop01 linked to another post that I think answers the _why_ better: https://stackoverflow.com/a/423668/6544256. "(I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation." – Eugene Triguba Jan 16 '23 at 01:54
0

In Python, when a variable is defined within a function, it is considered a local variable and is only accessible within that function. However, if a variable is defined outside of any function, it is considered a global variable and is accessible throughout the entire program. When a function modifies a global variable, it creates a new local variable with the same name, which shadows the global variable. This local variable exists only within the scope of the function and is separate from the global variable. To modify the global variable, you have to use the global keyword to specify that you are referring to the global variable, not the local one. The reason for this behavior is to prevent accidental modification of global variables. By default, a function can only read the value of a global variable, not modify it. This ensures that the function does not accidentally change the value of a global variable that might be used in other parts of the program. Using the global keyword explicitly indicates that the developer intends to modify the global variable and makes it clear that the change will have an effect outside the scope of the function. to modify the global variables you can do following

a = 0
def func():
    global a
    a+=2
func()
print(a) # should print 2
ahtasham nazeer
  • 137
  • 1
  • 7