|An Introduction to Python|
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
RRP £12.95 ($19.95)
Sales of this book support the Python Software Foundation! Get a printed copy>>>
5.7 More on Conditions
The conditions used in
if statements can
contain any operators, not just comparisons.
The comparison operators
not in check whether a value
occurs (or does not occur) in a sequence. The operators
is not compare whether two objects are really the same object; this
only matters for mutable objects like lists. All comparison operators
have the same priority, which is lower than that of all numerical
Comparisons can be chained. For example,
a < b == c tests
a is less than
b and moreover
Comparisons may be combined using the Boolean operators
or, and the outcome of a comparison (or of any other Boolean
expression) may be negated with
not. These have lower
priorities than comparison operators; between them,
the highest priority and
or the lowest, so that
A and not B or C is equivalent to
(A and (not B)) or C.
As always, parentheses can be used to express the desired composition.
The Boolean operators
or are so-called
short-circuit operators: their arguments are evaluated from
left to right, and evaluation stops as soon as the outcome is
determined. For example, if
C are true but
B is false,
A and B and C does not evaluate the
C. When used as a general value and not as a
Boolean, the return value of a short-circuit operator is the last
It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,
>>> str1, str2, str3 = ", 'Trondheim', 'Hammer Dance' >>> non_null = str1 or str2 or str3 >>> non_null 'Trondheim'
Note that in Python, unlike C, assignment cannot occur inside expressions.
C programmers may grumble about this, but it avoids a common class of
problems encountered in C programs: typing
= in an expression when
== was intended.
|ISBN 0954161769||An Introduction to Python||See the print edition|