In which order is an if statement evaluated in Python

后端 未结 5 1857
醉酒成梦
醉酒成梦 2020-12-03 20:56

If you have an if statement where several variables or functions are evaluated, in which order are they evaluated?

if foo > 5 or bar > 6:
    print \'f         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 21:19

    Python's or operator short-circuits and it will be evaluated left to right:

    if (foo > 5) or (bar > 6):
        print 'foobar'
    

    If foo > 5, then bar > 6 will not even be tested, as True or will be True. If foo isn't > 5, then bar > 6 will be tested.

提交回复
热议问题