Loops¶
Let’s review the while loop:
while a test is True, keep doing a suite of things
>>> x = 4
>>> while x > 0:
... print(x)
... x = x - 1
...
4
3
2
1
We can imagine iterating over a list using the following:
>>> counts = [1, 2, 3, 4, 5]
>>> i = 0
>>> while i < len(counts):
... count = counts[i]
... print(count)
... i = i + 1
...
1
2
3
4
5
But honestly, that’s a bit of a pain, because we are going to do this a lot, so we have a way of spelling that in a cleaner format:
>>> counts = [1, 2, 3, 4, 5]
>>> for count in counts:
... print(count)
...
1
2
3
4
5
Suites of Commands
Python is one of only a small number of languages that uses indentation to control what is “inside” a loop or if-statement. Most languages use {} braces or pairs of words, such as do and done.
for var in a,b,c,d
do
echo "Variable is ${var}"
ls ${var}
done
#! /usr/bin/env python
# iterforxiny.py
from __future__ import print_function
measurements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print('Squares')
total = 0
for item in measurements:
print(item, item ** 2)
total += item **2
print('Sum of Squares:', total)
loops can “nest” further loops (or other structures)
#! /usr/bin/env python
# iternest.py
from __future__ import print_function
rows = [
['Lightseagreen Mole', 24.0, -0.906, 0.424, -2.13, 0.0, 'green'],
['Indigo Stork', 51.0, 0.67, 0.742, 0.9, 9.0, 'yellow'],
]
for i,row in enumerate( rows ):
print('rows[{}]'.format( i ))
for measurement in row[1:-1]:
print(' {}'.format( measurement ))
Note
The enumerate
function we use in the above sample can be thought of as
doing this:
result = []
for i in range( len( rows )):
result.append( (i,rows[i]))
return result
but is actually implemented in a more efficient manner.
#! /usr/bin/env python
# iterfilter.py
from __future__ import print_function
measurements = range( 30 )
print('Odd Triple Squares')
total = 0
rest = 0
for item in measurements:
if item == 25:
print('25 is cool, but not an odd triple')
elif item % 2 and not item % 3:
print(item, item ** 2)
total += item **2
print('Sum of Odd Triple Squares:', total)
Exercise¶
construct lists by iterating over other lists
use conditions to only process certain items in a list
use conditions and a variable to track partial results
#! /usr/bin/env python
# iterexercise.py
rows = [
['Lightseagreen Mole', 24.0, -0.906, 0.424, -2.13, 0.0, 'green'],
['Springgreen Groundhog', 77.0, 1.0, -0.031, -32.27, 25.0, 'red'],
['Blue Marten', 100.0, -0.506, 0.862, -0.59, 16.0, 'yellow'],
['Red Bobcat', 94.0, -0.245, 0.969, -0.25, 36.0, 'green'],
['Ghostwhite Falcon', 31.0, -0.404, 0.915, -0.44, 49.0, 'green'],
['Indigo Stork', 51.0, 0.67, 0.742, 0.9, 9.0, 'yellow'],
]
# Create 2 lists holding the first two columns of *numeric* data
# (second and third columns)
# Print those items in the second column which are greater than 20 and less than 90
# Print the largest value in the third column