Python Practice › Loop Programs › Program 16
Sum of 1 to n
Write a Python program to find the sum of all natural numbers from 1 to n.
Input
n = 50
Output
1275 | formula: 1275
Approach
- Add each number to a running total.
Solution
n = 50total = 0for i in range(1, n + 1): total += iprint(total, "| formula:", n * (n + 1) // 2)Output
1275 | formula: 1275
Line by line
Line 5
The formula n(n+1)/2 confirms the loop’s answer.
Learn the concept
New to this topic? Read the lesson, then come back.