Sum of First N Natural Numbers

Print the sum of first n natural numbers.

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

What's going on

Accumulate sum by adding each number.

Key Concepts:

Initialize sum to 0
Loop from 1 to n
Add each number to sum
Formula: n * (n + 1) / 2 (but we use loop)