python : local variable is referenced before assignment

Question:

Here is my code :

x = 1
def poi(y):
        # insert line here

def main():
    print poi(1)

if __name__ == "__main__":
    main()

If following 4 lines are placed, one at a time, in place of # insert line here

 Lines         | Output
---------------+--------------
1. return x    | 1 
2. x = 99      |
   return x    | 99
3. return x+y  | 2 
4. x = 99      | 99  

In above lines it seems that global x declared above function is being used in case 1 and 3

But ,

x = x*y      
return x

This gives

error : local variable 'x' is reference before assignment

What is wrong in here ?

Asked By: navyad

||

Answers:

When you want to access a global variable, you can just access it by its name. But if you want to change its value, you need to use the keyword global.

try :

global x
x = x * y      
return x

In case 2, x is created as a local variable, the global x is never used.

>>> x = 12
>>> def poi():
...   x = 99
...   return x
... 
>>> poi()
99
>>> x
12
Answered By: Faruk Sahin

When Python sees that you are assigning to x it forces it to be a local variable name. Now it becomes impossible to see the global x in that function (unless you use the global keyword)

So

Case 1) Since there is no local x, you get the global

Case 2) You are assigning to a local x so all references to x in the function will be the local one

Case 3) No problem, it’s using the global x again

Case 4) Same as case 2

Answered By: John La Rooy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.