Sum of Squares Up to N
Accumulate the squares of one through n using Python. Students distinguish squaring each term from squaring a total and trace a running sum through the loop.
1# Take n as input2n = int(input("Enter n: "))34# Calculate sum of squares5sum_squares = 06for i in range(1, n + 1):7 sum_squares += i * i89print(f"Sum of squares: {sum_squares}")
Output
Enter n: 5 Sum of squares: 55
In this one
- Square before accumulation
- Keep a running total
- Distinguish two different formulas
How it works
- 1
Initialize sum_squares to zero.
- 2
Add i * i for each integer through n.
- 3
Print the combined square total.
Edge cases
What is returned for n = 0?
What is returned for n = 0?
Zero, because there are no terms.
Is ^ the power operator in Python?
Is ^ the power operator in Python?
No. ^ is bitwise XOR; this code uses multiplication for a square.
What's going on
Each iteration computes i * i before adding that square to sum_squares. The accumulator starts at zero.
For n equal to three, the terms are one, four, and nine, totaling fourteen. This is not (1 + 2 + 3) squared, which would be thirty-six. The final print displays only the combined result after all terms have been processed.
What is returned for n = 0? Zero, because there are no terms.
Is ^ the power operator in Python? No. ^ is bitwise XOR; this code uses multiplication for a square.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is added when i = 4?
Pick an answer to check it.
Question 2
What is returned for n = 0?
Pick an answer to check it.
Questions people ask
What is returned for n = 0?
Zero, because there are no terms.
Is ^ the power operator in Python?
No. ^ is bitwise XOR; this code uses multiplication for a square.
What is added when i = 4?
16.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum