Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Say it once, run it many times

Imagine a teacher who makes you write "I will not talk in class" 100 times. You wouldn't want to type it out 100 times in code. A loop says it once and the computer repeats it.

A for loop runs its lines once for every value in a range. In Python, range(1, 6) gives 1, 2, 3, 4 and 5. A box called i takes each value in turn. Watch out: the end of a range is not included, so to reach 5 you write 6.

The end is not included: a range that stops at 6 gives you 1 to 5.
In code
for i in range(1, 6):
    ...   # runs 5 times

A running total

Say you want to add up 1 to 5. Keep a box called total, and start it at zero before the loop begins. On each pass of the loop, add the current number into it.

When the loop ends, the total holds the answer. The box lives outside the loop so that each pass can see what the previous one left behind. If you made the box inside the loop, it would start over on every pass.

Make the total before the loop, so every pass can add to it.
In code
total = 0
for i in range(1, 6):
    total = total + i
Adding 1 to 5
1
0
2
1
3
2
4
3
5
4
i
i
1
total
1

Pass one: i is 1. Add it to the total, which goes from 0 to 1.

Move 1 of 5