And why we don't do everything one way or the other: performance vs. cost

# Count the number of lines in a file
reader = open("data.txt", "r")
number = 0
for line in reader:
number = number + 1
reader.close()
print number, "values in file"
9 lines in file

What about mean?

# Find the mean.
reader = open("data.txt", "r")
total = 0.0
number = 0
for line in reader:
total = total + line
number = number + 1
reader.close()
print "mean is", total / number
Traceback (most recent call last): File "mean-read-broken.py", line 7, in <module> total = total + line TypeError: unsupported operand type(s) for +: 'float' and 'str'

Data in file is text, so we need to convert

# Find the mean.
reader = open("data.txt", "r")
total = 0.0
number = 0
for line in reader:
value = float(line)
total = total + value
number = number + 1
reader.close()
print "mean is", total / number
mean is 2.77777777778

for data in test_cases:
result = sum_by_threes(data)
print data, "=>", result
to sum_by_threes given a list data:
result = []
for i in range(0, len(data), 3):
limit = min(i+3, len(data))
sum = sum_from(data, i, limit)
result.append(sum)
to sum_from given a list data, and start and end indices:
sum = 0
for i in range(start, end):
sum += data[i]

The computer doesn't care one way or another

But what we need is a way to write our programs in pieces, then combine the pieces