search

Home  >  Q&A  >  body text

涉及逻辑运算的python表达式的运算顺序

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

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:33:29

    Calculate from left to right

    Brackets don’t change that fact

    reply
    0
  • ringa_lee

    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 == 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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:33:29

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

    reply
    0
  • Cancelreply