What's the value of short-circuit of Python?

前端 未结 4 1213
太阳男子
太阳男子 2021-01-24 13:46

I\'m learning the book named Data Structures & Algorithms in Python.

On Page 12 that introduce the Logical Operators, it writes:

4条回答
  •  感动是毒
    2021-01-24 14:21

    I can't understand exact meaning of the second paragraph. In C, we can use the &&(logical and) as the following expression: (i != 0) && (j / i > 0) to prevent the error of a division by zero. So then, could I use the expression (i != 0) and ( j / i > 0) in Python as C to get the same effect? Is my understanding to the passage right?

    Yes

    What's the usage of or as a short-circuit to constructing Boolean expressions as said in the second paragraph ?

    As an example:

    if (y is None) or (x not in y):
    

    where y is either a list of things or None which in this case we want to treat a bit like an empty list, but x not in None would be an error.

    Or:

    (i  == 0) or (j / i > 0)
    

    The final question is about the grammar of had the prior test not succeeded in the second paragraph. I this it should be "an error condition that can had the prior test not succeeded", am I right?

    No, your phrasing is not correct grammar.

    If you have X and/or Y, X is the first or 'prior' test, Y is the second, and it's possible that X is false and trying to evaluate Y will cause an error.

提交回复
热议问题