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 109 views
2 answers 249 views
2 answers 244 views
2 answers 210 views
2 answers 530 views
2 answers 222 views
...