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.
1. Predict: What will happen?
Look at for loop code and predict what it will output.
2. Study: Worked Example
Step through a for loop example with explanations.
3. Investigate: Trace the Code
Track variable values as a for loop executes.
4. Modify: Arrange the Blocks
Drag and drop code blocks into the correct order.
5. Learn: The Accumulator Pattern
Learn how to use loops to calculate totals.
6. Test: Knowledge Quiz
Test your understanding of for loops.
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
# 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