+ 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)
6 Respostas
+ 5
N = int(input())
sum = 0
for i in range(N + 1):
sum += i
print(sum)
+ 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.
+ 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.
+ 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)))
+ 1
Shadoff
I think sum(range(...)) would work, too
+ 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.