62
3 Loops and Branching
Other for Loop Structures In this book, you will occasionally meet for loops
with a different structure, and as an example, take a look at 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 k will become 1, 2 and 3,
respectively. In the second iteration, they will become 4, 5 and 6, respectively, and
so on. Thus, the printout reads
1 2 3
4 5 6
6 7 8
As usual, each of i, j and k can be used in any desirable way within the loop.
3.1.3 Combining for Loop and Array
Often, loops are used in combination with arrays, so we should understand how that
works. To reach this understanding, it is beneficial to do an example with just a
small array.
Assume the case is to compute the average height of family members in a family
of 5. We may choose to store all the heights in an array, which we then run through
by use of a for loop to compute the average. The code (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.5 m as the average height, which compares
favorably to a simple hand calculation. What happens here, is that we first sum up 3
all the heights being stored in the array h, before we divide by the number of family
members N (i.e., just like we would do by hand). Observe how sum is initialized to 0
before entering the loop, and that with each iteration, a new height is added to sum.
Note that the loop variable i takes on the integer index values of the array, which
start with 0 and end with N − 1.
3 Note this way of using a loop to compute a sum, it is a standard technique in programming.
Précédent

- 84/350

Suivant