Python - logical evaluation order in “if” statement

前端 未结 4 1466
耶瑟儿~
耶瑟儿~ 2020-12-03 12:02

In Python we can do this:

if True or blah:
    print(\"it\'s ok\") # will be executed

if blah or True: # will raise a NameError
    print(\"it\'s not ok\")
         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-03 13:04

    It's the way the operators logical operators, specifically or in python work: short circuit evaluation.

    To better explain it, consider the following:

    if True or False:
        print('True') # never reaches the evaluation of False, because it sees True first.
    
    if False or True:
        print('True') # print's True, but it reaches the evaluation of True after False has been evaluated.
    

    For more information see the following:

    • The official python documentation on boolean operations
    • A stack overflow question regarding short circuitry in python

提交回复
热议问题