Next: Expression lists and Up: Expressions and conditions Previous: Comparisons

Boolean operations

Boolean operations have the lowest priority of all Python operations:


condition:      or_test | lambda_form
or_test:        and_test | or_test "or" and_test
and_test:       not_test | and_test "and" not_test
not_test:       comparison | "not" not_test
lambda_form:	"lambda" [parameter_list]: condition

In the context of Boolean operations, and also when conditions are used by control flow statements, the following values are interpreted as false: None, numeric zero of all types, empty sequences (strings, tuples and lists), and empty mappings (dictionaries). All other values are interpreted as true.

The operator not yields 1 if its argument is false, 0 otherwise.

The condition [tex2html_wrap1198]first evaluates [tex2html_wrap1200]; if [tex2html_wrap1202]is false, its value is returned; otherwise, [tex2html_wrap1204]is evaluated and the resulting value is returned.

The condition [tex2html_wrap1206]first evaluates [tex2html_wrap1208]; if [tex2html_wrap1210]is true, its value is returned; otherwise, [tex2html_wrap1212]is evaluated and the resulting value is returned.

(Note that and and or do not restrict the value and type they return to 0 and 1, 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 0, not ''.)

Lambda forms (lambda expressions) have the same syntactic position as conditions. They are a shorthand to create anonymous functions; the expression lambda arguments: condition yields a function object that behaves virtually identical to one defined with def name (arguments): return condition. See section for the syntax of parameter lists. Note that functions created with lambda forms cannot contain statements.


guido@cwi.nl