English 中文(简体)
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.

最佳回答

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.

问题回答

This is how the Python boolean operators work.

From the documentation (the last paragraph explains why it is a good idea that the operators work the way they do):

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)

The operator not yields True if its argument is false, False otherwise.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

(Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or foo yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not foo yields False, not .)

The reason is that Python evaluates boolean expression using the actual values of the variables involved, instead of restricting them to True and False values. The following values are considered to be false:

  • None
  • False
  • 0 of any numeric type
  • empty sequence or set ( , (), [], {})
  • user-defined types with __nonzero__() or __len__() method that returns 0 or False

See the Truth Value Testing section of the Python documentation for more information. In particular:

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

Try using parentheses to make the expression non-ambiguous. The way it is, you re getting:

(foo == bar and spam) or eggs




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签