12.8 A function that accumulates

From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period2 exercises2 graded tests

README.md

12.8 A function that accumulates

Read first in the book: 12.6 Decoding a Function, 12.7 Type Annotations.

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.

def mylen(seq):
    c = 0 # initialize count variable to 0
    for _ in seq:
        c = c + 1   # increment the counter for each item in seq
    return c

print(mylen("hello"))
print(mylen([1, 2, 7]))

Check your understanding: a mixed-up code puzzle in the book.

Check your Understanding

Exercise 1

1. Write a function named total that takes a list of integers as input, and returns the total value of all those integers added together.

Open the 01 folder and edit main.py. Run Tests checks it.

Exercise 2

2. Write a function called count that takes a list of numbers as input and returns a count of the number of elements in the list.

Open the 02 folder and edit main.py. Run Tests checks it.

For teachers

12.8 A function that accumulates

Students read Foundations of Python Programming's “A function that accumulates” in CS Room and work through its 2 Python coding exercises (2 graded).

  • Time: 1 class period
  • Tests: 2 in 2 graded exercises, set up for you when you import the lesson

Reading first

Exercises

FolderGradingTests
01Autograded1
02Autograded1