+ 4
Help please sum 1âŠ100
N = int(input()) sum = 0 while N>=0: sum += N+1 print (sum)
13 Respostas
+ 4
# Or
N = int(input())
print (sum(range(N+1)))
+ 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
+ 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.
+ 2
Thanks
+ 2
#OR
x=int(input())
print(int((x**2+x)/2))
+ 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)
+ 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.
+ 1
l1=[]
for i in range(1,101):
l1.append(i)
print(sum(l1))
+ 1
Laxmi Pokhriyal Use x = int(input()) instead of x = input(int())
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)
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?
0
Can you pls explain why difference came in output
Especially that 0 and even before You
- 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