🔄 For Loops

Learn how to repeat code a specific number of times using for loops.

What you'll learn:

  • Understand that for loops repeat code a specific number of times
  • Trace the execution of a for loop step by step
  • Use the range() function to control iterations
  • Apply the accumulator pattern to calculate totals

Learning Path

Follow these activities in order. Each builds on the previous one.

Key Vocabulary

iteration

One pass through a loop. If a loop runs 5 times, that's 5 iterations.

for loop

A loop that repeats a specific number of times.

range()

A function that generates a sequence of numbers. range(5) gives 0, 1, 2, 3, 4.

loop variable

The variable that changes each time through the loop. In for i in range(5), i is the loop variable.

loop body

The indented code that gets repeated. It runs once for each iteration.

accumulator

A variable that collects values during a loop, like a running total.

Quick Reference

for_loop_syntax.py
# Basic for loop
for i in range(5):
    print(i)    # Prints: 0, 1, 2, 3, 4

# range(start, stop)
for i in range(1, 6):
    print(i)    # Prints: 1, 2, 3, 4, 5

# range(start, stop, step)
for i in range(10, 0, -1):
    print(i)    # Counts down: 10, 9, 8, ... 1