+ 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)

21st Jun 2022, 8:12 PM
M Heather Fleming
M Heather Fleming - avatar
8 odpowiedzi
+ 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) )
21st Jun 2022, 10:01 PM
Jayakrishna 🇮🇳
+ 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))
21st Jun 2022, 8:19 PM
Simon Sauter
Simon Sauter - avatar
+ 1
Jayakrishna🇮🇳 this has helped so much!! Thank you :)
22nd Jun 2022, 9:19 PM
M Heather Fleming
M Heather Fleming - avatar
+ 1
N=int(input()) sum=0 for i in range(1,N+1): sum+=i print(sum)
22nd Jun 2022, 9:21 PM
M Heather Fleming
M Heather Fleming - avatar
0
Jayakrishna🇮🇳 , do i define sum? Is this where i should store the result?
21st Jun 2022, 9:34 PM
M Heather Fleming
M Heather Fleming - avatar
0
You're welcome.. That's perfect for the specific task done by loop..
23rd Jun 2022, 5:51 PM
Jayakrishna 🇮🇳
- 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.
21st Jun 2022, 8:16 PM
Jayakrishna 🇮🇳