This is a beginner's class. I just need help verifying if this code is correct, or edit the parts that need fixing.

n = int(input("Enter a number"))
sum = 0
for i in range(1,n+1):
    sum = sum + i
    print("The sum is:", sum)


Do you want to display a cumulative sum every time the loop executes? That's what you do now. If not - if you want to only display the final sum - you need to de-indent your print.


You can do the whole sum using the actual sum function, like this:

total = sum(range(1, n + 1))

Note that you should not call a variable sum, because that shadows the built-in sum function.

Calculating the sum

This doesn't actually need a loop or a call to sum at all. Math will tell you that the entire sum will evaluate to \$n(n + 1)/2\$; an example of equivalence:

$$ \begin{align} 1 + 2 &= 3\\ \frac{2 * 3}{2} &= 3 \end{align} $$

  • 1
    \$\begingroup\$ The generator expression is unnecessary. Simply sum the range: total = sum(range(1, n + 1)). \$\endgroup\$ – AJNeufeld Jun 24 '20 at 14:22
  • \$\begingroup\$ @AJNeufeld nice! \$\endgroup\$ – Reinderien Jun 24 '20 at 14:23
  • 1
    \$\begingroup\$ A 'graphical proof' of sum(1 to n) = n(n+1)/2 \$\endgroup\$ – Jan Kuiken Jun 24 '20 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.