Doing it again and again
Repeat some lines for every number in a range, keeping a running total. About 9 minutes.
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.
for i in range(1, 6):
... # runs 5 timesA 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.
total = 0
for i in range(1, 6):
total = total + i- i
- 1
- total
- 1
Pass one: i is 1. Add it to the total, which goes from 0 to 1.
How many times does for i in range(1, 6) run its lines?
- A5 times
- B6 times
- C4 times
Show the answer
5 times. i takes the values 1, 2, 3, 4 and 5. The end value, 6, is not included.
Add up to n
Return the sum of all whole numbers from 1 up to n, including n. The sum can get bigger than an int can hold, so the result is a long.
n = 5 → 15
0 ≤ n ≤ 100,000