1

I input 10 to the below sequence, the it prints sum = 56 I list what sum includes, they are 1,2,3,4,5,6,7,8,9,10. I wonder what's wrong with the calculation of sum.

=======================================

n = int(input('input number?'))

sum = 1


for i in range(1,n+1,1):

     sum += i


print(sum)
3
  • You are starting the loop from one and also have initialized the sum with 1. It is a logical error rather than a programmatical one. Try setting up sum = 0. Note: default steps are 1 in Python loop, so the third param in the range is unnecessary. Commented Mar 24, 2021 at 7:03
  • Also, sum is a builtin, change it to something like 'sumval' instead. For instance: "sum([1,2,3,4,5,6,7,8,9,10])" should give you "55". Commented Mar 24, 2021 at 7:06
  • It works now! Thank you. Commented Mar 24, 2021 at 7:09

2 Answers 2

1

That's because you first define sum = 1. The true result is 55 but you increment it by yourself.

true code is below

n = int(input('input number?'))
result = sum(range(1, n+1))

You should not use sum as a variable name because sum is a built-in function. And in this case, you can calculate summantion by sum so easily.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't know why the variable 'sum' is initialized to 1. It should be 0. You will get the correct result. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.