How to calculate the sum of first N natural numbers in Python

2 Answers

0 votes
# 1 + 2 + 3 + 4 + ... + N

n = 10
summ = 0

while n > 0:
    summ += n
    n -= 1

print("The sum is:", summ)

'''
run:

The sum is: 55

'''

 



answered May 26, 2017 by avibootz
edited May 26, 2017 by avibootz
0 votes
# 1 + 2 + 3 + 4 + ... + N

n = 10
summ = 0

summ = n / 2 * (n + 1)

print("The sum is:", summ)

'''
run:

The sum is: 55.0

'''

 



answered May 26, 2017 by avibootz
edited May 26, 2017 by avibootz

Related questions

1 answer 221 views
2 answers 390 views
2 answers 380 views
2 answers 341 views
2 answers 640 views
2 answers 334 views
...