There are situations where an expression involves a simple condition
and a full-sized
statement is distracting syntatic
overkill. Python has a handy logic operator that evalutes a condition,
then returns either of two values depending on that condition.
Most arithmetic and logic operators have either one or two values.
An operation that applies to a single value is called
unary. For example
abs(b) are examples of unary operations: unary negation and
unary absolute value. An operation that applies to two values is called
binary. For example,
a*b shows the binary multiplication
The if-else operator trinary. It involves a conditional expression
and two alternative expressions. Consequently, it doesn't use a single
special character, but uses two keywords:
The basic form of the operator is
. Python evaluates the
condition first. If the condition is
True, then the
left-hand expression is evaluated, and that's the value of the operation.
If the condition is
False, then the else expression
is evaluated, and that's the value of the operation.
Here are a couple of examples.
The intent is to have an English-like reading of the statement. "The
average is the sum divided by the count if the count is non-zero;
otherwise the average is None".
The wordy alterative to the first example is the following.
if count != 0:
This seems like three extra lines of code to prevent an error in the
rare situation of there being no values to average.
Similarly, the wordy version of the second example is the
if n % 2 == 0:
oddSum = oddSum + n
For this second example, the original statement registered our
intent very clearly: we were summing the odd values. The long-winded
if-statement tends to obscure our goal by making it just one branch of the