Page - 66 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 66 -
Text of the Page - 66 -
66 3 LoopsandBranching
Fig. 3.1 Vertical position ofball
The loop will run as long as the conditiony[i] >= 0 evaluates toTrue. Note
that the programmer introduced a variable by the name i, initialized it (i = 0)
beforetheloop,andupdatedit (i = i + 1) in theloop.So,eachtimethecondition
y[i] >= 0 evaluates to True, i is explicitly increased by 1, allowing a check of
successiveelements in thearrayy.
Whentheconditiony[i] >= 0evaluatestoFalse,programexecutionproceeds
with thecodelinesafter the loop.Thismeansthat, afterskippingthecomments, the
timeofflight isprinted,followedbyaplottingof theheights(toallowaneasycheck
of the timeofflight).
Reporting the Answer Remember that the height is computed at chosen points
in time only, so, most likely, we do not have the time for when the height is
exactlyzero.Thus,reportingt[i]asthetimeofflight isanapproximation.Another
alternative,couldbetoreport0.5*(t[i-1] + t[i])as theanswer,reasoningthat
sincey[i] isnegative(which is whythe loop terminated),t[i]mustbe too large.
Runningthe Program Ifyou run thisprogram,youget theprintout
Time of flight (in seconds): 0.917918
and the plot seen in Fig.3.1. The printed time of flight seems consistent with what
wecan readoff fromthe plot.
3.2.2 CharacteristicsofaTypicalwhileLoop
LoopStructureandInterpretation Thestructureofa typicalwhile loopmaybe
putupas
while some_condition: # Loop header
<code line 1> # 1st line in loop body
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