Discrepancy in using global variable in a function in Python

Viewed 79

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?

2 Answers

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.

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

Related