Python Practice › Basic Programs › Program 35

Sum of natural numbers

EasyBasic Programs · 35 of 40

Write a Python program to find the sum of the first n natural numbers (1 + 2 + … + n).

Advertisement
Input
n = 100
Output
5050

Approach

  1. Loop and add, or use the formula n(n + 1)/2.

Solution 1: loop

Python
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

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs