Page - 121 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 121 -
Text of the Page - 121 -
5.4 MakingOurOwnModule 121
position = y(v_initial, t) # compute all positions (over T)
plt.plot(t, position, βb--β)
plt.xlabel(βTime (s)β)
plt.ylabel(βVertical position (m)β)
plt.show()
return
if __name__ == β__main__β:
application()
The code in application represents the main program and should be under-
standable from what we have learned previously. Note that, like we have done
here, it is usually a good idea to print some information about how the program
works.
Testing Asasimple testof thecodeinvertical_motion.py,wemightcompare
theoutput tohandcalculations,aswedidbefore. InChap.6,however,wewill learn
howtesting ought to be donevia dedicated test functions.These test functionsmay
berunindifferentways.Onealternative,however, is to includeanoptionwithin the
testblock,whichallowstheuser torunthroughthe test functionswheneverwanted,
butmoreabout that later.
PlacingImport Statements in Our Module
Note that ifwehaveimportstatements inourmodule, it ispossible toruninto
troubleifwedonotplace themat the topof thefile (whichisaccordingto the
general recommendation).
With the following sketchy example module, it will work fine to import
some_function in another program and use it (since, when importing
some_function, the importofnumpy isdone).
import numpy as np
def some_function(n):
a = np.zeros(n)
...
return r
def application():
....
n = 10
r = some_function(n)
...
return
if __name__ == β__main__β:
application()
One choice that would not work in the same way, however, would
be to instead have the import statement import numpy as np after
if __name__ == β__main__β: . Then, this import statement would not
be run ifsome_function is imported foruse inanotherprogram.
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