0

I have the following code

data = 10
def func():
    print data
    data += 1
    print data

Here, the code fails with the following error

UnboundLocalError: local variable 'data' referenced before assignment

i have read this post and understood that my code is creating a local variable named data and so, its not trying to look in the global scope. But, i am trying to print data before the assignment. So, why isn't data accessible before the assignment?

NOTE: I know that if i use global keyword, variable will be accessible. My question is why it isn't accessible before the assignment operation. Because, only when assigning, it creates the variable in local scope.

rawwar
  • 4,834
  • 9
  • 32
  • 57

1 Answers1

1

When you run the below code:

data = 10
def func():
    print(data)
func()

You will get output as:

10

But if you try to run the below code:

data = 10
def func():
    print(data)
    data += 1
    print(data)

It will give an error:

UnboundLocalError: local variable 'data' referenced before assignment

The reason is:

We are trying to assign a value to a variable in an outer scope.

A variable can't be both local and global inside of a function. So Python decides that we want a local variable due to the assignment to data inside of func(), so the first print statement before the definition of data throws the error message above. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to explicitly state this by using the keyword global

To change the value of global variable use of global variable.

d = 10
def func():
    global data
    data +=1
    print(data)

func()
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20
  • Hi, Thanks for your answer. But, i was actually looking for an indepth understanding of why this is happening. Reason being, I see that when i just use a variable to print, python uses LOAD_GLOBAL where as when an assignment operator is present, it uses LOAD_FAST. how is this distinction done. i tried looking at ast. Couldn't understand much. – rawwar Jan 17 '20 at 08:58
  • 1
    @InAFlash This is the reason for that : ```A variable can't be both local and global inside of a function. So Python decides that we want a local variable due to the assignment to data inside of func(), so the first print statement before the definition of data throws the error message above. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to explicitly state this by using the keyword global``` – Vaibhav Jadhav Jan 17 '20 at 09:10