# Calculate and displays the sum of all numbers from 1 to 20

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)


## Bug?

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.

## Sum

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}

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