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?

3
  • 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. Commented Jul 11, 2020 at 20:33
  • local variable is created only when you use assignment Commented Jul 11, 2020 at 20:36
  • Does this answer your question? Use of "global" keyword in Python Commented Jul 11, 2020 at 20:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
I agree with you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.