综合编程

Python Scope Error

微信扫一扫,分享到朋友圈

Python Scope Error

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
or not.

So in the first two examples you assign to a variable x
– regardless whether you do that before or after the print
statement – so it means there is a local variable x
.

In your last example you do
not assign to x

: x
is not an assignment, only x =
(or x +=
, etc.) are assignments. So it is an expression
. Therefore there is in the last example no local variable x
and the one out of the function scope is used.

Bootstrap timepicker not showing time selecter option

上一篇

TypeScript: Why, How, and What We Learned

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

Python Scope Error

长按储存图像,分享给朋友