以下代码并不报错,而我理解在"point 1"处如果先运算小括号里面的表达式,而y并不存在,不应该报错吗?难道发现x == 10的短路运算优先于小括号里面的表达式运算?
将这一行中x == 10改为x == 100后报错了,这个理解没问题。
# coding: utf-8
if __name__ == "__main__":
x = 100
if x == 10:
y = 200
# no y exist here
if x == 10 and (y - 1 == 199): # point 1
print "ok"
ringa_lee2017-04-18 09:33:29
This is normal, I suggest you read this post:
The core idea of and and or operations in Python——Short-circuit logic
In your example, and
前的x == 10
为False
, 所以短路其后所有and
表达式,直到有or
出现,输出and
左侧表达式到or
的左侧,参与接下来的逻辑运算, 然而并没有发现, 所以位于and
右侧的表达式(y - 1 == 199)
is ignored directly, equivalent to air;
If x == 10
改为x == 100
, 这时and
左侧为True
, 右侧的表达式不能短路, 要参与逻辑运算, 此时由于局部变量y
has not been created, so an error will be reported. The error content should be similar to this
NameError: name 'y' is not defined