68
3 Loops and Branching
3.3 Branching (if, elif and else)
Very often in life, 5 and in computer programs, the next action depends on the
outcome of a question starting with “if”. This gives the possibility of branching
into different types of action depending on some criterion.
As an introduction to branching, let us “build up” a little program that evaluates
a water temperature provided by the program user.
3.3.1 Example: Judging the Water Temperature
Assume we want to write a program that helps us decide, based on water temperature
alone (in degrees Celcius), whether we should go swimming or not.
One if-test As a start, we code our program simply as
T = float(input(’What is the water temperature? ’))
if T > 24:
print(’Great, jump in!’)
# First line after if part
Even if you have never seen an if test before, you are probably able to guess what
will happen with this code. Python will first ask the user for the water temperature.
Let us assume that 25 is entered, so that T becomes 25 through the assignment
(note that, since the input returns a string, we convert it to a float before assigning
to T). Next, the condition T > 24 will evaluate to True, which implies that the print
command gets executed and “Great, jump in!” appears on the screen.
To the contrary, if 24 (or lower) had been entered, the condition would have
evaluated to False and the print command would not have been executed. Rather,
execution would have proceeded directly to the line after the if part, i.e., to
the line # First line after if part, and continued from there. This would
mean, however, that our program would give us no response if we entered a water
temperature of 24, or lower.
Two if-tests Immediately, we realize that this is not satisfactory, so (as a “first fix”)
we extend our code with a second if test, as
T = float(input(’What is the water temperature? ’))
if T > 24:
# testing condition 1
print(’Great, jump in!’)
if T <= 24:
# testing condition 2
print(’Do not swim. Too cold!’)
# First line after if-if construction
This will work, at least in the way that we get a planned printout (“Do not swim.
Too cold!”) also when the temperature is 24, or lower. However, something is not
quite right here. If T is 24 (or lower), the first condition will evaluate to False, and
5 Some readers may perhaps be puzzled by this sentence, bringing in such a huge thing as life itself.
The truth is, that this sentence is as deep as it appears. My dear co-author Hans Petter Langtangen
wrote this sentence well into his cancer treatment. Hans Petter passed away on October 10th, 2016,
a few months after the 1st edition of this book was published.
Précédent

- 90/350

Suivant