3.1.5 The Accumulator Pattern

Unit: Unit 3: Loops • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Calculate the sum of integers from 1 to 5 using an accumulator
total_sum = 0  # 1. Initialize accumulator BEFORE the loop

for number in range(1, 6):
    total_sum += number  # 2. Update accumulator DURING each iteration
    print("Added:", number, "| Running Total:", total_sum)

# 3. Use accumulated result AFTER the loop completes
print("Final Sum:", total_sum)
Open in Live Interactive Python Sandbox →