Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of First N Natural Numbers

Add the first n natural numbers using a Python accumulator. Beginners trace a running total, the inclusive upper bound, and what an empty loop leaves behind.

BeginnerPhase 2 - Level 1: Basic LoopingExample 3 of 14
sum-of-first-n-natural-numbers.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Calculate sum
5sum = 0
6for i in range(1, n + 1):
7 sum += i
8
9print(f"Sum of first {n} natural numbers: {sum}")

Output

Enter n: 5
Sum of first 5 natural numbers: 15

In this one

  • Maintain a running sum
  • Include n in a range
  • Understand empty totals

How it works

  1. 1

    Initialize sum to zero.

  2. 2

    Add each integer from one through n.

  3. 3

    Print the total after the loop finishes.

Walk through Sum of First N Natural Numbers

n = 3

  1. 1.sum = 0 before the loop.
  2. 2.i = 1 gives sum = 1; i = 2 gives sum = 3.
  3. 3.i = 3 gives sum = 6, then the loop ends.

Edge cases

What happens for n = 0?

What happens for n = 0?

The loop is empty and the result stays zero.

What happens for negative n?

What happens for negative n?

The loop also stays empty; the program does not reject that input.

What's going on

The running total starts at zero. Each loop value from one through n is added to the same variable rather than replacing the previous total.

For n equal to three, the total changes from zero to one, three, then six. The final print runs after the loop. The variable name sum shadows Python's built-in sum function, which is legal but best avoided in larger programs.

What happens for n = 0? The loop is empty and the result stays zero.

What happens for negative n? The loop also stays empty; the program does not reject that input.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does += do here?

Pick an answer to check it.

Question 2

What happens for n = 0?

Pick an answer to check it.

Questions people ask

What happens for n = 0?

The loop is empty and the result stays zero.

What happens for negative n?

The loop also stays empty; the program does not reject that input.

What does += do here?

Adds to the existing total.