Syllabus Lesson 14 of 239 · Control Flow
Control Flow

Watch: a Loop Adding Up

You just wrote loops that build up a result. That pattern, start a total at 0, then fold in one item at a time, is the single most common shape in all of programming. It is easy to read the code and still not see it happen.

So watch it. Press play and follow a for loop walk a list, light up each number in turn, and add it into a running total. Step through it, then answer the check.

total = 0
for n in [3, 1, 4, 1, 5]:
    total = total + n   # fold each item into the running total

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output