+ 1
Sum of Consecutive Numbers
I am having a hard time with this. The program tells me my expected output is 64261. But if N is the input, how does the output equate to 64261? I feel like the code doesnât need a loop to solve, as it should just run through range(0,(100+1)) once and give an output. Can someone tell me what I am doing wrong? I know Iâm missing the addition function, how do I write adding over a range? N=int(input) Sum(0,(100+1)) Print(Sum)
7 Answers
+ 2
M Heather Fleming
sum(range(1,10)) returns sum of numbers from 1to 9. you can store result in a variable for later use. If only need to display then just display by print( sum( range(1, 10) )
+ 1
This *can* be done using the sum function and range. But since it's about learning to use loops you should use one.
Doing it with sum() and range() would look like this:
sum(range(N+1))
+ 1
Jayakrishnađźđł this has helped so much!! Thank you :)
+ 1
N=int(input())
sum=0
for i in range(1,N+1):
sum+=i
print(sum)
0
Jayakrishnađźđł , do i define sum? Is this where i should store the result?
0
You're welcome..
That's perfect for the specific task done by loop..
- 1
it asking sum of number from 0 to N
Not 0 to 100..
next sum(0, 100) is invalid. Pass an iterator to sum function.. Use the range function and then store the result or display directly..
N=int(input) # use this N value
Sum(0,(100+1)) # this invalid and no effect, store result
Print(Sum) # sum is undefined.
edit:
as this is loop usage practice, try to use loop.