Page - 31 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 31 -
Text of the Page - 31 -
1.6 Plotting,PrintingandInputData 31
dt = 0.55
t = t0 + 0*dt; g = t*sin(t)
print(β{:6.2f} {:8.3f}β.format(t, g))
t = t0 + 1*dt; g = t*sin(t)
print(β{:6.2f} {:8.3f}β.format(t, g))
t = t0 + 2*dt; g = t*sin(t)
print(β{:6.2f} {:8.3f}β.format(t, g))
Running thisprogram,we get theprintout
2.00 1.819
2.55 1.422
3.10 0.129
Observe that the columns are nicely aligned here. With the formatting, we effec-
tively control the width of each column and also the number of decimals. The
numbers in each column will then become nicely aligned under each other and
writtenwith thesameprecision.
To the contrary, if we had skipped the detailed formatting, and rather used a
simplercall toprint like
print(t, g)
thecolumnswouldbe printedas
2.0 1.81859485365
2.55 1.42209347935
3.1 0.128900053543
Observe that theniceandeasy-to-readstructureof theprintoutnowisgone.
1.6.3 Printing:Thef-String
We should briefly also mention printing by use of f-strings. Above, we printed the
valuesofvariablesv1andv2,being10.0and20.0, respectively.Oneof thecallswe
used toprintwas (repeatedhere foreasy reference)
print(βv1 is {} \nv2 is {}β.format(v1, v2)) # \n gives new line
and it producedtheoutput
v1 is 10.0
v2 is 20.0
However, if we rather skip.format(v1, v2), and instead introduceanf in front
of the string, we can produce the very same outputby the followingsimpler call to
print:
print(fβv1 is {v1} \nv2 is {v2}β)
So, f-strings21 are quitehandy!
21 Read more about f-strings athttps://www.python.org/dev/peps/pep-0498.
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik