Page - 62 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 62 -
Text of the Page - 62 -
62 3 LoopsandBranching
Other for Loop Structures In this book, you will occasionally meet for loops
witha differentstructure,andasanexample, take a lookat this:
for i, j, k in (1, 2, 3), (4, 5, 6), (6, 7, 8):
print(i, j, k)
Here, in the first iteration, the loop variables i, j and kwill become 1, 2 and 3,
respectively. In the second iteration, they will become 4, 5 and 6, respectively, and
soon.Thus, theprintout reads
1 2 3
4 5 6
6 7 8
Asusual, eachofi,jandkcanbe used inanydesirablewaywithin the loop.
3.1.3 CombiningforLoopandArray
Often, loopsareusedincombinationwitharrays,soweshouldunderstandhowthat
works. To reach this understanding, it is beneficial to do an example with just a
small array.
Assumethecase is tocomputetheaverageheightof familymembers ina family
of5.We maychoose to storeall the heights in anarray,whichwe then run through
byuseofafor looptocomputetheaverage.Thecode(average_height.py)may
look like this:
import numpy as np
N = 5
h = np.zeros(N) # heights of family members (in meter)
h[0] = 1.60; h[1] = 1.85; h[2] = 1.75; h[3] = 1.80; h[4] = 0.50
sum = 0
for i in [0, 1, 2, 3, 4]:
sum = sum + h[i]
average = sum/N
print(’Average height: {:g} meter’.format(average))
When executed, the code gives 1.5m as the average height, which compares
favorably to a simple handcalculation.What happenshere, is that we first sum up3
all theheightsbeingstored in thearrayh, beforewedividebythenumberof family
membersN (i.e., just likewewoulddobyhand).Observehowsum is initialized to0
beforeentering the loop,and that with each iteration, a newheight is added tosum.
Note that the loop variablei takes on the integer index values of the array, which
startwith 0andendwithN−1.
3 Note thisway of using a loop to compute a sum, it is a standard technique inprogramming.
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