Python boolean expression and or

后端 未结 4 2172
小蘑菇
小蘑菇 2020-12-01 21:17

In python if you write something like

foo==bar and spam or eggs

python appears to return spam if the boolean statement is true and eggs oth

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 21:35

    The operators and and or are short-circuiting which means that if the result of the expression can be deduced from evaluating only the first operand, the second is not evaluated. For example if you have the expression a or b and a evaluates to true then it doesn't matter what b is, the result of the expression is true so b is not evaluated. They actually work as follows:

    • a and b: If a is falsey, b is not evaluated and a is returned, otherwise b is returned.
    • a or b: If a is truthy, b is not evaluated and a is returned, otherwise b is returned.

    Falsey and truthy refer to values that evaluate to false or true in a boolean context.

    However this and/or idiom was useful back in the days when there was no better alternative, but now there is a better way:

    spam if foo==bar else eggs
    

    The problem with the and/or idiom (apart from it being confusing to beginners) is that it gives the wrong result if the condition is true but spam evaluates to a falsey value (e.g. the empty string). For this reason you should avoid it.

提交回复
热议问题