this code gives an ‘Unbound Error’ (discussed in this query Python variable scope error)
x=3 def f(): print x x+=3
The reason for this (as given in the answer) is that once assignment operator has been used ‘x’ become a local variable and since ‘x’ does not have a value attached to it one cannot increase it by 3. But check out this code
x=3 def f(): print x x=3
This time it doesn’t seem that ‘x’ does have a value and hence there shouldn’t be any problem, but the same error occurs.
UnboundLocalError: local variable 'x' referenced before assignment
If python has already created a local variable ‘x’ after reading the statement ‘x=3’ then why does it not print ‘x’?
It is also interesting to note here that this code produces no error
x=3 def f(): print x x
the out being ‘3’ (when f() is called)
This confuses me a lot, isn’t this time too ‘x’ being declared inside ‘f()’ then shouldn’t python add this ‘x’ to its list of local variable?
Well the question to which you link clearly states that:
Python treats variables in functions differently depending on whether you assign values to them from within the function
So in the first two examples you assign to a variable
– regardless whether you do that before or after the
statement – so it means there is a local variable
In your last example you do
not assign to
is not an assignment, only
, etc.) are assignments. So it is an expression
. Therefore there is in the last example no local variable
and the one out of the function scope is used.