Python Fundamentals ยท Control Flow

for Loops, range and enumerate

Repeat once per item: numbers from range, counting down with a step, and getting both position and item with enumerate.

for_range.py

total = 0
for n in range(1, 5):        # 1, 2, 3, 4: the end is not included
    total = total + n

for i in range(10, 0, -4):   # start, stop, step: counts down
    print(i)

for index, colour in enumerate(["red", "blue"]):
    print(index, colour)
print(total)

Step by step

  1. total is created with the value 0.
  2. range(1, 5) gives 1, 2, 3, 4. The stop value, 5, is never included.
  3. total = 0 + 1.
  4. n changes from 1 to 2.
  5. total changes from 1 to 3.
  6. n changes from 2 to 3.
  7. total changes from 3 to 6.
  8. n changes from 3 to 4.
  9. total = 6 + 4 = 10.
  10. Python moves to the next item of the loop: for n in range(1, 5): # 1, 2, 3, 4: the end is not included.
  11. range(10, 0, -4) starts at 10 and steps by -4: 10, 6, 2. It stops before reaching 0.
  12. It prints 10.
  13. i changes from 10 to 6.
  14. It prints 6.
  15. i changes from 6 to 2.
  16. It prints 2.
  17. Python moves to the next item of the loop: for i in range(10, 0, -4): # start, stop, step: counts down.
  18. enumerate hands out pairs: (0, "red"), then (1, "blue").
  19. It prints 0 red.
  20. index changes from 0 to 1. colour changes from 'red' to 'blue'.
  21. It prints 1 blue.
  22. Python moves to the next item of the loop: for index, colour in enumerate(["red", "blue"]).
  23. range made the numbers, the step counted down, and enumerate gave positions with the items. total ended at 1 + 2 + 3 + 4 = 10.