28
1 The First Few Steps
One Variable and Text Combined Assume there is a variable v1 in your program,
and that v1 has the value 10.0, for example. If you want your code to print the value
of v1, so that the printout reads
v1 is 10.0
you can achieve that with the following line in your program:
print(’v1 is {}’.format(v1))
This is a call to the function print with “an argument composed of two parts”. The
first part reads v1 is {} enclosed in single quotes (note the single quotes, they
must be there!), while the second part is .format(v1). The single quotes of the
first part means that it is a string (alternatively, double quotes may be used). 19 That
string contains a pair of curly brackets {}, which acts as a placeholder. The brackets
tell Python where to place the value of, in this case, v1, as specified in the second
part .format(v1). So, the formatting creates the string v1 is 10.0, which then
gets printed by print.
Several Variables and Text Combined Often, we have more variables to print,
and with two variables v1 and v2, we could print them by
print(’v1 is {}, v2 is {}’.format(v1, v2))
In this case, there are two placeholders {}, and—note the following: the order of v1
and v2 given in .format(v1, v2) will dictate the order in which values are filled
into the preceding string. That is, reading the string from left to right, the value of
v1 is placed where the first {} is found, while the value of v2 is placed where the
second {} is located.
So, if v1 and v2 have values 10.0 and 20.0, respectively, the printout will read
v1 is 10.0, v2 is 20.0
When printing the values of several variables, it is often natural to use one line for
each. This may be achieved by using \n as
print(’v1 is {} \nv2 is {}’.format(v1, v2))
# \n gives new line
which will produce
v1 is 10.0
v2 is 20.0
We could print the values of more variables by a straight forward extension of what
was shown here.
Note that, if we had accidentally switched the order of the variables as
print(’v1 is {}, \nv2 is {}’.format(v2, v1))
where .format(v2, v1) is used instead of .format(v1, v2)), we would have
got no error message, just an erroneous printout where the values are switched:
v1 is 20.0
v2 is 10.0
19 Previously, we have met objects of type int and float. A string is an object of type str.
Précédent

- 50/350

Suivant