Python Practice › Basic Programs › Program 35
Sum of natural numbers
Write a Python program to find the sum of the first n natural numbers (1 + 2 + … + n).
Input
n = 100
Output
5050
Approach
- Loop and add, or use the formula n(n + 1)/2.
Solution 1: loop
n = 100total = 0for i in range(1, n + 1): total += iprint(total)Output
5050
Line by line
Lines 3-4
Adds 1, 2, 3 … 100 one at a time.
Solution 2: formula
n = 100print(n * (n + 1) // 2, sum(range(1, n + 1)))Output
5050 5050
Line by line
Line 2
The formula gives the answer instantly; // keeps it an integer. sum(range(...)) is the one-line loop version.
Learn the concept
New to this topic? Read the lesson, then come back.