涉及逻辑运算的python表达式的运算顺序
高洛峰
高洛峰 2017-04-18 09:31:29
0
3
405

以下代码并不报错,而我理解在"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"
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
伊谢尔伦

Calculate from left to right

Brackets don’t change that fact

左手右手慢动作

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 == 10False, 所以短路其后所有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
巴扎黑

1!!!!!!!!!!!!!!!!!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template