Python Practice › Loop Programs › Program 16

Sum of 1 to n

EasyLoop Programs · 16 of 90

Write a Python program to find the sum of all natural numbers from 1 to n.

Advertisement
Input
n = 50
Output
1275 | formula: 1275

Approach

  1. Add each number to a running total.

Solution

Python
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.

More loop programs

← All 90 Loop Programs

Leave a Comment