Web-Books
in the Austria-Forum
Austria-Forum
Web-Books
Informatik
Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Page - 31 -
  • User
  • Version
    • full version
    • text only version
  • Language
    • Deutsch - German
    • English

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 -

Image of the Page - 31 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition

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.
back to the  book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition"
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
Web-Books
Library
Privacy
Imprint
Austria-Forum
Austria-Forum
Web-Books
Programming for Computations – Python