Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 9 of 25

for loops and range()

A for loop repeats a block once for every item in a sequence. With range(), you can repeat a fixed number of times.

for i in range(5):
    print(i)      # 0 1 2 3 4

range() has three forms. The stop value is never included.

  • range(5) gives 0, 1, 2, 3, 4
  • range(2, 6) gives 2, 3, 4, 5
  • range(10, 0, -2) gives 10, 8, 6, 4, 2

A common pattern is to keep a running total: start a variable at 0 before the loop and add to it inside the loop. Print it after the loop, without indentation, so it is shown once.

total = 0
for n in range(1, 6):
    total += n
print(total)   # 15

Key takeaways

  • range(5) gives 0, 1, 2, 3, 4. The stop value is never included.
  • range(start, stop, step) can start elsewhere, take bigger steps, or count down with a negative step.
  • The loop body is the indented block after the for line, and it runs once for each value.
  • Looping directly over a list or a string, for item in items:, is usually clearer than counting positions.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.