Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

syntax - Python boolean expression and or

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 otherwise. Could someone explain this behaviour? Why is the expression not being evaluated like one long boolean?

Edit: Specifically, I'm trying to figure out the mechanism why 'spam' or 'eggs' is being returned as the result of the expression.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...