Sum of First N Natural Numbers in Python
N(N+1)/2. A loop also works. The formula is O(1) and easier to get wrong with / vs //.
BeginnerBasic Python ProgramsExample 20 of 25
sum-of-first-n-natural-numbers.py
1# Program to find the sum of first N natural numbers23n = int(input("Enter a positive integer N: "))45if n <= 0:6 print("Please enter a positive integer.")7else:8 total = n * (n + 1) // 29 print("Sum of first", n, "natural numbers is:", total)
Output
Enter a positive integer N: 10 Sum of first 10 natural numbers is: 55
In this one
- N*(N+1)//2, check N=10 → 55
- // keeps it an int
What's going on
1+2+...+N = N(N+1)/2. For N=10 that's 55. Gauss, school-story, whatever.
n * (n + 1) // 2 uses integer division so you get 55 not 55.0. Regular / is fine too if you don't mind the float.
A for loop that adds 1 through N is clearer and slower. For N=10 you will not notice. For N=10 million you will.
n <= 0 is rejected. The formula still "works" for 0 (sum is 0) but "first 0 natural numbers" is a bad prompt.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.