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)

14th Mar 2021, 3:22 PM
Daniel Lopez
8 Respostas
14th Mar 2021, 3:33 PM
Soumik
Soumik - avatar
+ 10
without loop: N = int(input()) print(N*(N+1)//2)
14th Mar 2021, 4:08 PM
visph
visph - avatar
0
visph Wow awesome solution. Thanks for sharing!
14th Mar 2021, 4:18 PM
Soumik
Soumik - avatar
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)
14th Mar 2021, 7:40 PM
you are smart. you are brave.
you are smart. you are brave. - avatar
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
18th May 2021, 8:33 AM
Calvin Thomas
Calvin Thomas - avatar
0
N = int(input()) total = sum([sub for sub in range(1, N+1)]) print(total)
26th Aug 2021, 9:56 PM
Shan Romesh
Shan Romesh - avatar
- 2
N = int(input()) count = N x = range(1, N +1) for i in x: N = i + N print(N - count)
18th May 2021, 8:09 AM
Ислам Алб
Ислам Алб - avatar
- 3
N = int(input()) t=0 for e in range(0,N+1): t+=e print(t)
17th Jun 2021, 2:04 PM
Patel Armin
Patel Armin - avatar