Seite - 70 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 70 -
Text der Seite - 70 -
70 3 LoopsandBranching
out with the simplest version of the code, complexity is added step by step, before
arrivingat thefinalversion.Ateachstep,youmakesure thecodeworksasplanned.
Such a procedure is generally a good idea, and we will address it explicitly again,
whenwe programa(slightly)morecomprehensivecase inSect.4.2.
3.3.2 TheCharacteristicsofBranching
Amoregeneral formofanif-elif-elseconstructionreads
if condition_1: # testing condition 1
<code line 1>
<code line 2>
...
elif condition_2: # testing condition 2
<code line 1>
<code line 2>
...
elif condition_3: # testing condition 3
<code line 1>
<code line 2>
...
else:
<code line 1>
<code line 2>
...
# First line after if-elif-else construction
Here we see an if part, two elif parts and an else part. Note the compulsory
colon and indented code lines (a block of statements) in each case. As with loops,
indents are conventionally 4 spaces. In such an arrangement, there may be “any”
numberofelifparts (alsonone)and theelsepartmay,ormaynot,bepresent.
When interpreting an arrangement like this, Python starts checking the condi-
tions, one after the other, from the top. If a condition (here, eithercondition_1,
condition_2or condition_3) evaluates to True, the corresponding code lines
areexecuted,beforeproceedingdirectly to thefirst lineafter thewholearrangement
(here, to the line # First line after if-elif-else construction). This
means that any remaining tests, and theelsepart, are simply skipped! If none of
theconditionsevaluate toTrue, theelsepart (whenpresent) is executed.
3.3.3 Example:FindingtheMaximumHeight
We have previously modified ball_plot.py from Sect.1.5 to find the time of
flight instead(seeball_time.py).Letusnowchangeball_plot.py inaslightly
differentway, so that the new programinstead finds the maximum height achieved
by the ball.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik