| Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 120 pages ISBN 0954161785 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
5.10 Boolean operations
Boolean operations have the lowest priority of all Python operations:
expressionor_test[ifor_testelsetest]|lambda_formor_testand_test|or_test"or"and_testand_testnot_test|and_test"and"not_testnot_testcomparison| "not"not_test
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.
The operator not yields True if its argument is false,
False otherwise.
The expression x if C else y first evaluates
C (not x); if C is true, x is evaluated and
its value is returned; otherwise, y is evaluated and its value is
returned. (Added in Python version 2.5)
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 ".)
| ISBN 0954161785 | Python Language Reference Manual | See the print edition |