5

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 ?

navyad
  • 3,752
  • 7
  • 47
  • 88

2 Answers2

6

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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
4

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
Faruk Sahin
  • 8,406
  • 5
  • 28
  • 34