Can anyone help me with this program i need only single final output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone help me with this program i need only single final output

N = int(input()) sum=0 n=1 for n in range(0,N+1): if n<=N: sum=sum+n n+=1 print(sum)

9th Mar 2021, 12:47 PM
Parthik
Parthik - avatar
4 Answers
+ 3
1. You shouldn't use sum as a variable name. It overwrites the built-in sum() function. I would suggest total instead 2. You don't need to set n=1 here ahead of the for loop. 3. You also don't need the if n<=N statement, since that is all that the range() function would output, it is guaranteed that n will be in the range of 0-N+1 and the check is redundant. To start at 1 just change the first argument of range to 1. 4. Likewise, you don't need to increment n inside the loop, as that is handled by the range() function and the incremented value of n will be overwritten by the for loop with the same value anyhow. 5. I believe you actually want to print the total value after the for loop, not for each iteration, so you need to move this statement after and outside the loop. This leaves you with; N = int(input()) total = 0 for n in range(1, N+1): total += n print(total)
9th Mar 2021, 1:04 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
You could also use the Gauss formula. N = int(input()) # total = (len(range(1, N+1)/2) * (1 + N) # in this case len will always be equal to N total = int((N/2) * (1 + N)) print(total)
9th Mar 2021, 1:12 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
ChaoticDawg Thank you
9th Mar 2021, 1:13 PM
Parthik
Parthik - avatar
9th Mar 2021, 1:00 PM
Parthik
Parthik - avatar