Page - 114 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 114 -
Text of the Page - 114 -
114 5 SomeMorePythonEssentials
moveswithout any air resistance.7 As with built-in modules, we will see that func-
tionality may be imported in the usual ways, e.g., asimport vertical_motion,
whichallowseasy reuseofmodule functions.
5.4.1 ANaiveImport
Before turning to the making of our vertical motion module, we will do some
“warm-up”testingwitha previousscriptofours, just toenlightenourselvesa bit.
Let us pick ball_function.py from Sect.4.1.1 (which addresses vertical
motion), and argue that, if this script is a module, we should be able to “import
it” asimport ball_function, right? This sounds like a reasonable expectation,
sowithout toodeep reasoning, let us just start there.
First, however, we better take another look at that code (after all, it has been a
while).Foreasyreference,wejust repeat thefewcodelinesofball_function.py
here:
def y(v0, t):
g = 9.81 # Acceleration of gravity
return v0*t - 0.5*g*t**2
v0 = 5 # Initial velocity
time = 0.6 # Just pick one point in time
print(y(v0, time))
time = 0.9 # Pick another point in time
print(y(v0, time))
We recognize the function definition of y and the two applications of that
function, involving a function call and a printout for each of the chosen points in
time.
Now, we previously thought of this code as a program, executed it, and got the
printouts.Whatwillhappennow,whenweratherconsideritamoduleandimportit?
Here iswhathappens:
In [1]: import ball_function
1.2342
0.52695
What?Printingofnumbers?Weaskedforan import,8 not somethingthat looks like
programexecution!
Thethingis, thatwhenanymoduleis imported,Pythondoesactuallyexecutethe
modulecode(!), i.e., functiondefinitionsarereadandstatements(outsidefunctions)
executed. This is Python’s way of bringing module content “to life”, so that, e.g.,
7 The reader who is into physics, will know that the computations done here, work equally well if
the object has some simultaneous horizontal motion. In that case, our computations apply to the
vertical component of the motion only, not the motionas a whole.
8 Doingtheimportdifferently, e.g., likefrom vertical_motion import y,wouldstillgive the
printouts! Also if the import were done ina script.
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