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 accumulator variable
Section titled “The accumulator variable”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().
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.
A condition inside the loop
Section titled “A condition inside the loop”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().
Notice the double indentation: if is inside the loop (4 spaces), and print is inside the if (8 spaces).
Looping over text
Section titled “Looping over text”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().
Missions
Section titled “Missions”Be Gauss
+15 XP ✓ CompletedCalculate 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().
Sum of the evens
+15 XP ✓ CompletedFind 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().
Star pyramid
+15 XP ✓ CompletedCombine 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().
Next lesson: while — “as long as this is true, repeat”. And you’ll come face to face with the famous infinite loop trap. Continue →