+ 4

Help please sum 1…100

N = int(input()) sum = 0 while N>=0: sum += N+1 print (sum)

31st Mar 2022, 10:27 AM
Salim Foks
13 odpowiedzi
+ 4
# Or N = int(input()) print (sum(range(N+1)))
31st Mar 2022, 10:40 AM
SoloProg
SoloProg - avatar
+ 3
N = int(input()) sum = 0 while N>0: #loop runs till N=0 from input sum += N #adds N,N-1,N-2,...1 N -= 1 #decrese N print(sum) #print total sum
31st Mar 2022, 10:30 AM
Jayakrishna 🇮🇳
+ 3
Sum of first `N` natural numbers is N(N+1)/2. Example: 1.....100 N = 100 sum = (100 x 101)/2 = 5050 Simply use this formula. Saves a lot of unnecessary computation and reduces the code to one line.
31st Mar 2022, 11:38 AM
Abhishek Tandon
Abhishek Tandon - avatar
+ 2
Thanks
31st Mar 2022, 10:32 AM
Salim Foks
+ 2
#OR x=int(input()) print(int((x**2+x)/2))
31st Mar 2022, 10:56 AM
NEZ
NEZ - avatar
+ 2
#alternative because you said from 1 to 100, so no need for input. s=1 while s<101: sum+=s s+=1 print(sum)
31st Mar 2022, 11:05 AM
HungryTradie
HungryTradie - avatar
+ 2
It is due to execution order. The code in the deepest parenthesis is running first in our case. int(input()) : input() runs first and prompt the user to enter a value, then turns the input into an integer. input(int()) : int() runs first and because nothing is mentioned inside the parenthesis, it automatically generate an integer with the value 0 then finally run input(). The reason why 0 is printed is because input() basically prints what is inside its parenthesis while waiting for user to enter a value.
1st Apr 2022, 11:23 AM
Orisa
Orisa - avatar
+ 1
l1=[] for i in range(1,101): l1.append(i) print(sum(l1))
1st Apr 2022, 4:24 AM
MAYUR SHINDE
+ 1
Laxmi Pokhriyal Use x = int(input()) instead of x = input(int())
1st Apr 2022, 11:08 AM
Orisa
Orisa - avatar
0
Here is a solution with the method you started to write. N = int(input()) I = 1 sum = 0 while I <= N: sum += I I += 1 print(I)
1st Apr 2022, 6:22 AM
Orisa
Orisa - avatar
0
I first wrote the code x = input() print("You entered: " + x) Suppose one entered 8 Result was - You entered: 8 But when i changed code to x = input(int()) print("You entered: " + x) It came 0You entered: 8 Can anyone explain?
1st Apr 2022, 11:06 AM
Himanshu Pokhriyal
0
Can you pls explain why difference came in output Especially that 0 and even before You
1st Apr 2022, 11:11 AM
Himanshu Pokhriyal
- 1
def sum(L): s = 0 for i in L: s = s + i print(s) sum([i for i in range(1,101)]) best code for sum
1st Apr 2022, 9:31 PM
Rayan
Rayan - avatar