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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…