Skip to content Skip to sidebar Skip to footer

Python : Local Variable Is Referenced Before Assignment

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,

Solution 1:

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

Solution 2:

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>>>defpoi():...  x = 99...return x...>>>poi()
99
>>>x
12

Post a Comment for "Python : Local Variable Is Referenced Before Assignment"