+ 1
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?
4 Réponses
+ 6
Just wanted to remind you not to use built-in function name (sum) for your variable name 👌
+ 4
total = 0
for n in range(1, N+1):
total += n
print(total)
this should do the job
+ 1
Thank you
+ 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.