A function that accumulatesΒΆ

We have used the len function a lot already. If it weren’t part of python, our lives as programmers would have been a lot harder.

Well, actually, not that much harder. Now that we know how to define functions, we could define len ourselves if it did not exist. Previously, we have used the accumlator pattern to count the number of lines in a file. Let’s use that same idea and just wrap it in a function definition. We’ll call it mylen to distinguish it from the real len which already exists. We actually could call it len, but that wouldn’t be a very good idea, because it would replace the original len function, and our implementation may not be a very good one.

        exceptions-7: Rearrange the code statements to match the activecode window above. (This is an exercise in noticing where the indenting and outdenting happens, and where the return statement goes.)
def mylen(x):
   c = 0 # initialize count variable to 0
   for y in x:
      c = c + 1   # increment the counter for each item in x
   return c
print mylen("hello")
print mylen([1, 2, 7])
Next Section - Decoding a Function