Skip to content

Calculate with loops

A teacher hands young Carl Gauss a task: “add up all the numbers from 1 to 100” — hoping to keep the kid busy for a long while. Gauss finds the answer in a few seconds. You, on the other hand, have Python. 😏

The trick: before the loop, set up an accumulator variable (total = 0), and inside the loop, add to it:

Inputs (for input())

One value per line — read in order by input().

Output
 

This technique is called the accumulator, and you’ll run into it everywhere in programming: tallying points, counting money, calculating an average…

By the way, there’s a shortcut for total = total + i: total += i — same thing, just shorter.

Module 02 meets Module 03: you can put an if inside a loop. For example, let’s print only the even numbers from 1 to 20:

Inputs (for input())

One value per line — read in order by input().

Output
 

Notice the double indentation: if is inside the loop (4 spaces), and print is inside the if (8 spaces).

for doesn’t only work with numbers — it can walk through the letters of a piece of text too:

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Be Gauss

+15 XP

Calculate the sum of all the numbers from 1 to 100. Gauss’s answer was 5050 — yours should be too!

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Sum of the evens

+15 XP

Find the sum of only the even numbers from 1 to 50. Loop + condition + accumulator — three weapons combined!

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Star pyramid

+15 XP

Combine the "*" * i trick from Module 01 with a loop: print a pyramid that grows from 1 star to 5 stars.

Inputs (for input())

One value per line — read in order by input().

Output
 

Next lesson: while — “as long as this is true, repeat”. And you’ll come face to face with the famous infinite loop trap. Continue →