Seite - 63 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 63 -
Text der Seite - 63 -
3.1 TheforLoop 63
Running ThroughCode“byHand”
It is appropriate to stress that much understanding is often developedby first
goingthroughcode“byhand”, i.e. just read thecodewhiledoingcalculations
byhand,beforecomparingthesehandcalculations towhat thecodeproduces
whenrun (oftensome print commandsmust be inserted in thecode toenable
detailedcomparison).
Thus,tomakesureyouunderstandtheimportantdetails inaverage_height.
py, youare encouraged to go through that code byhandright now.Also, in a
copy, insert a print commandin the loop, so that you can compare the output
fromthatprogramtoyourowncalculations, iterationby iteration.
3.1.4 UsingtherangeFunction
At this point, the observant reader might argue: “Well, thisfor loop seems handy,
butwhat if the loopmustdoa really largenumberof iterations? If the loopvariable
is to runthroughhundredsofnumbers,wemustspendallday typingthosenumbers
into the loopheader”!
An Example This is where the built-in range function enters the picture. When
called, therangefunctionwillprovideintegersaccordingto theargumentsgivenin
thefunctioncall.Forexample,wecouldhaveusedrange inaverage_height.py
by just changingtheheader from
for i in [0, 1, 2, 3, 4]: # original code line
to
for i in range(0, 5, 1): # new code line
Here, range(0, 5, 1) is a function call, where the function range is told to
provide the integers from 0 (inclusive) to 5 (exclusive!) in steps of 1. In this case,
range(0, 5, 1)will provide exactly those numbers that we had in the original
code, i.e., the loop variableiwill run through the same values (0, 1, 2, 3 and 4) as
before,andprogramcomputationsstay the same.
Withalittle interactivetest,wemayconfirmthattherangefunctionprovidesthe
promised numbers.However, since what is returned from therange function is an
object of typerange, the number sequence is not explicitly available.4 Converting
the rangeobject toa list, however,does the trick.
In [1]: x = range(0, 5, 1)
In [2]: type(x)
Out[2]: range
In [3]: x
Out[3]: range(0, 5)
4 In Python 2, therange function returned the requested numbers asa list.
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