Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

BeginnerPhase 2 - Level 1: Basic LoopingExample 13 of 14
sum-of-squares-up-to-n.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Calculate sum of squares
5sum_squares = 0
6for i in range(1, n + 1):
7 sum_squares += i * i
8
9print(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. 1

    Initialize sum_squares to zero.

  2. 2

    Add i * i for each integer through n.

  3. 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.