3

I was just playing around with Python and I came across something interesting which I didn't quite understand. The code goes as follows:

a = 1
def function():
  print(a)
function()
print(a)

Here, a is a global variable and I used it in my function and the result was:

1
1

I was able to use a global variable locally in my function without having to use global a in my function.

Then, I experimented further with this:

a = 1
def function():
  a = a+1
  print(a)
function()
print(a)

When I ran this code, an error showed up and it said that the local variable a was referenced before assignment. I don't understand how before it recognized that a was a global variable without global a but now I need global a like this

a = 1
def function():
  global a
  a = a+1
  print(a)
function()
print(a)

in order for this code to work. Can someone explain this discrepancy?

fireball.1
  • 1,413
  • 2
  • 17
  • 42
  • When you assign a variable in a function, you create a local variable. Now that you've done that you have a global `a` and a local `a`. Now you say `a + 1`, which `a` are you referring to. Python wants you to be explicit here. When you just read the value, there's no confusion because there is only the global `a`. – Mark Jul 11 '20 at 20:33
  • local variable is created only when you use assignment – fireball.1 Jul 11 '20 at 20:36
  • Does this answer your question? [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – Brian McCutchon Jul 11 '20 at 20:40

2 Answers2

3

You can read the value from a global variable anytime, but the global keyword allows you to change its value.

This is because when you try and set the a variable in your function, by default it will create a new local function variable named a. In order to tell python you want to update the global variable instead, you need to use the global keyword.

Daniel Geffen
  • 1,777
  • 1
  • 11
  • 16
0

When creating "=" ,a new variable inside a function python does not check if that variable is a global variable, it treats that new variable as a new local variable, and since you are assigning it to itself and it does not exist locally yet, it then triggers the error

Diego Suarez
  • 901
  • 13
  • 16
  • That's not an analogy; that is *literally* how Python works. An assignment in a function makes the name local to the function, even if the assignment statement isn't executed at run-time. Locality is a *static* property. – chepner Jul 11 '20 at 21:58
  • I agree with you. – Diego Suarez Jul 12 '20 at 01:01