Loops and collections · 10 min

Repeat with loops

Use for, while, and range to repeat a task.

A for loop takes one value from an iterable at a time. range(1, 4) supplies the numbers 1, 2, and 3. Code at the same indentation as the loop runs after the loop ends.

A while loop repeats while its condition stays true. Update the condition inside the loop so it can finish. break leaves a loop early and continue skips to the next iteration.

Follow the example

The accumulator starts at zero before the loop.

Try it yourself

Use a for loop to add all the numbers from 1 through 5. Print only the final total.

Target output

15
Show a hint

The stop value of range is excluded. Remove the countdown section for this exercise.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
total = 0
for number in range(1, 6):
    total += number
print(total)