The natural numbers are 1, 2, 3 and so on. This program adds the first n of them, first with a loop and then with a formula that needs no loop at all.
The program
n = int(input("Add the numbers from 1 to: ")) total = 0 i = 1 while i <= n: total += i i += 1 print(f"Sum of 1 to {n} = {total}")
Typed in this example: 100. Press Run to type your own.
Add the numbers from 1 to: 100 Sum of 1 to 100 = 5050
How it works
totalstarts at 0. Each pass of the loop adds the currentito it, then movesion by one.- The loop stops when
ibecomes larger thann. - If the user types 0, the loop body never runs and the sum is 0, which is the correct answer.
Two shorter ways
sum() adds up everything in a range. The formula n * (n + 1) // 2 gives the same answer with one multiplication, however large n is.
n = 100 print(sum(range(1, n + 1))) print(n * (n + 1) // 2)
5050 5050
The formula works because you can pair the numbers from both ends: 1 + 100, 2 + 99, 3 + 98, and so on. Each pair adds up to n + 1, and there are n / 2 pairs. // is whole-number division, so the result is an int and not 5050.0.
Related programs: Sum of a series.