To find the sum of n consecutive number from 1 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

To find the sum of n consecutive number from 1

N = int(input()) #your code goes here sum=int((N*(N+1))/2) print(sum) This is my program I have got the desired result but I want to do with the loop statement ( for an while) I was unable to get it Can anyone help me?

2nd Sep 2021, 1:41 PM
Nishant Kumar
4 Answers
+ 6
Just wanted to remind you not to use built-in function name (sum) for your variable name 👌
2nd Sep 2021, 1:48 PM
Ipang
+ 4
total = 0 for n in range(1, N+1): total += n print(total) this should do the job
2nd Sep 2021, 1:44 PM
Shahrull Fytri
Shahrull Fytri - avatar
+ 1
Thank you
2nd Sep 2021, 1:49 PM
Nishant Kumar
+ 1
Nishant Kumar Your code O(1) will be much more efficient than using a loop O(N), but there are plenty of good examples here for you to choose from if you want to use a loop for practice. Also, as Ipang suggests, don't use built-in names for your variables as it will overwrite the use of those names and may cause future bugs and errors in your code.
2nd Sep 2021, 7:53 PM
ChaoticDawg
ChaoticDawg - avatar