This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.
The flow of computer programs often needs to branch. That is, if a condition is met, we do one thing, and if not, we do another thing. A simple example is a function defined as $$ \begin{equation} f(x) = \left\lbrace\begin{array}{ll} \sin x, & 0\leq x\leq \pi\\ 0, & \hbox{otherwise} \end{array}\right. \tag{4} \end{equation} $$ In a Python implementation of this function we need to test on the value of \( x \), which can be done as displayed below:
def f(x): if 0 <= x <= pi: value = sin(x) else: value = 0 return value
if-else
test is
if condition: <block of statements, executed if condition is True> else: <block of statements, executed if condition is False>
When condition
evaluates to True
, the program flow branches into
the first block of statements. If condition
is False
, the program
flow jumps to the second block of statements, after the else:
line.
As with while
and for
loops, the block of statements are
indented.
Here is another example:
if C < -273.15: print '%g degrees Celsius is non-physical!' % C print 'The Fahrenheit temperature will not be computed.' else: F = 9.0/5*C + 32 print F print 'end of program'
The two print
statements in the if
block
are executed if and only if
C < -273.15
evaluates to True
. Otherwise, we jump over
the first two print
statements and carry out the computation and
printing of F
. The printout of end of program
will be
performed regardless of the outcome of the if
test since this
statement is not indented and hence neither a part of the if
block
nor the else
block.
The else
part of an if
test can be skipped, if desired:
if condition: <block of statements> <next statement>
For example,
if C < -273.15: print '%s degrees Celsius is non-physical!' % C F = 9.0/5*C + 32
In this case the computation of F
will always be carried out,
since the statement is not indented and hence not a part of the
if
block.
With the keyword elif
, short for else if, we can have
several mutually exclusive if
tests, which allows for
multiple branching of the program flow:
if condition1: <block of statements> elif condition2: <block of statements> elif condition3: <block of statements> else: <block of statements> <next statement>
The last else
part can be skipped if it is not needed.
To illustrate multiple branching we will implement a hat
function, which is widely used in advanced computer simulations
in science and industry. One example of a hat function is
$$
\begin{equation}
N(x) = \left\lbrace\begin{array}{ll}
0, & x < 0\\
x, & 0\leq x < 1\\
2-x, & 1\leq x < 2\\
0, & x \geq 2
\end{array}\right.
\tag{5}
\end{equation}
$$
The Python implementation associated with (5)
needs multiple if
branches:
def N(x): if x < 0: return 0.0 elif 0 <= x < 1: return x elif 1 <= x < 2: return 2 - x elif x >= 2: return 0.0
This code corresponds directly to the mathematical specification, which
is a sound strategy that help reduce the amount of errors in programs.
We could mention that there is another way of constructing the
if
test that results in shorter code:
def N(x): if 0 <= x < 1: return x elif 1 <= x < 2: return 2 - x else: return 0
As a part of learning to program, understanding this latter sample code is important, but we recommend the former solution because of its direct similarity with the mathematical definition of the function.
A popular programming rule is to avoid multiple return
statements in
a function - there should only be one return
at the end. We can do
that in the N
function by introducing a local variable, assigning
values to this variable in the blocks and returning the variable at
the end. However, we do not think an extra variable and an extra line
make a great improvement in such a short function. Nevertheless, in
long and complicated functions the rule can be helpful.
A variable is often assigned a value that depends on a
boolean expression. This can be coded using a common if-else
test:
if condition: a = value1 else: a = value2
Because this construction is often needed, Python provides a one-line syntax for the four lines above:
a = (value1 if condition else value2)
The parentheses are not required, but recommended style. One example is
def f(x): return (sin(x) if 0 <= x <= 2*pi else 0)
Since the inline if
test is an expression with a value, it can be used in
lambda functions:
f = lambda x: sin(x) if 0 <= x <= 2*pi else 0
The traditional if-else
construction with indented
blocks cannot be used inside
lambda functions because it is not just an expression (lambda functions
cannot have statements inside them, only a single expression).