+ 1

I need help guys. I'm a beginner in coding and I'm doing python

I'm trying to find the sum of first N number. From 1 to that number N. This was my code N = int(input()) sum = 1 for i in range( 1,N+1,1) sum += 1 print (N)

12th Jul 2021, 12:37 PM
Philippe Ezekiel
Philippe Ezekiel - avatar
6 odpowiedzi
+ 5
N = int(input()) sum = 0 for i in range(N + 1): sum += i print(sum)
12th Jul 2021, 12:40 PM
Apongpoh Gilbert
Apongpoh Gilbert - avatar
+ 3
Hint: The sum of all the natural numbers up to a number is equal to half the product of the number and the next one.
12th Jul 2021, 5:09 PM
Calvin Thomas
Calvin Thomas - avatar
+ 2
When you test your code on playground, you'll find that your output N is 1 too many. This is because your sum is already 1 before we enter the loop and start adding the numbers.
12th Jul 2021, 1:18 PM
Lisa
Lisa - avatar
+ 1
#creating list and then sum up: print(sum([i for i in range(1,N+1)])) #directly sum up, #without creating unnecessary list: print(sum(range(N+1)))
12th Jul 2021, 2:38 PM
Shadoff
Shadoff - avatar
+ 1
Shadoff I think sum(range(...)) would work, too
12th Jul 2021, 2:39 PM
Lisa
Lisa - avatar
+ 1
sum = 0 for i in range(1, 11): sum+=i print(sum) User input does not needed in this code You can use this code instead.
14th Jul 2021, 11:27 AM
Kaibalya Prasad Ojha
Kaibalya Prasad Ojha - avatar