Statement
Solution
Exercise 3.2: The Summation
One of the most common uses for loops is to accumulate a total. Write a program that sums all numbers from 1 to 100.
Your program should:
- Initialize a variable (e.g.,
total) to 0. - Use a For Loop to iterate from 1 to 100.
- Inside the loop, add the current number to your
totalvariable. - After the loop finishes, print the final result.
(Note: You do not need user input for this exercise).
Sample Interaction:
Input
Output
(None)
Calculating sum...
The sum of numbers from 1 to 100 is: 5050
Solution
This pattern is often called the "Accumulator Pattern". We start with zero and add to it repeatedly.
# 1. Initialize the accumulator
total_sum = 0
# 2. Loop from 1 to 100 (range stops before 101)
for i in range(1, 101):
total_sum = total_sum + i
# 3. Print the result outside the loop
print(f"The sum of numbers from 1 to 100 is: {total_sum}")
Key Concepts:
range(1, 101)includes 1 and goes up to, but not including, 101.+=is a shorthand operator.x += iis the same asx = x + i.- Placement of
print()matters! If it's inside the loop, it prints every step. If outside, it prints only the total.
Test Console
Run code to see output...