Building Answers with Loops

Introduction: A Loop That Answers a Question

Welcome back to Writing Complex Python Functions! In the first unit, our functions chose one answer out of several by testing conditions. In this second unit, they will do something different: build an answer out of many pieces of data, one item at a time.

Our program includes two functions for this lesson. sum_to(limit) adds up a range of integers, and count_long_words(text, min_length=5) counts how many words in a sentence are long enough. Later, the standalone countdown_text(start) example will show that the same accumulator pattern can build a string instead of a number; it is not part of the two-function program below. Running the program prints exactly this:

text
55
3

Everything in this lesson turns on one idea: when a loop lives inside a function, where we place return relative to that loop decides whether the function sees all the data or only the first item. We will meet the accumulator pattern, the post-loop return, and the deliberate early return.

The Accumulator Pattern: Initialize, Update, Return

Simple accumulator functions like the ones in this unit follow the same three-part shape. Searches, mutations, and side-effect loops can look different; here we focus on building one answer. Let's read sum_to with those three parts in mind.

Python
def sum_to(limit):
    """Return the sum of every integer from 1 through limit."""
    total = 0                       # accumulator lives in local scope
    for number in range(1, limit + 1):
        total += number
    return total                    # returned only after the loop finishes
  • total = 0 initializes the accumulator before the loop, so a place to collect results already exists when the first iteration starts.
  • total += number updates it inside the loop, once per item.
  • return total hands the finished value back after the loop.
Flow of the accumulator pattern from initialization through repeated updates to the final return

As we may recall from the previous course, total is a local variable: it is created fresh on every call and disappears when the call ends. Nothing outside the function can read it, so return is the only way its value escapes.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal