0
Python 3: sum of consecutive numbers
If a user inputs N, and I have to add up all numbers from 1 to N, what is wrong with this code? N = int(input()) #your code goes here for i in range (1,N+1): if sum == (i += i): print (sum)
8 Answers
+ 2
This might help.
https://code.sololearn.com/c7Us8liK73vP/?ref=app
+ 10
without loop:
N = int(input())
print(N*(N+1)//2)
0
visph Wow awesome solution. Thanks for sharing!
0
here is a list comprehension that would work as well.
N = int(input())
total = sum([sub for sub in range(1, N+1)])
print(total)
0
ŠŃŠ»Š°Š¼ ŠŠ»Š± Your code works just fine, but your procedural approach needs work, I guess. Here are some alternatives:
1.
sum = 0
for i in range(int(input())):
sum += i + 1
print(sum)
2.
sum = i = 0
n = int(input())
while i < n:
sum += i + 1
i += 1
print(sum)
3.
print(sum(range(1, int(input()) + 1)))
4.
n = int(input())
print(n * (n + 1) // 2)
Or
print((n:=int(input())) * (n + 1) // 2)
# I hope this helps
0
N = int(input())
total = sum([sub for sub in range(1, N+1)])
print(total)
- 2
N = int(input())
count = N
x = range(1, N +1)
for i in x:
N = i + N
print(N - count)
- 3
N = int(input())
t=0
for e in range(0,N+1):
t+=e
print(t)