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.
1# Take n as input2n = int(input("Enter n: "))34# Calculate sum5sum = 06for i in range(1, n + 1):7 sum += i89print(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
Initialize sum to zero.
- 2
Add each integer from one through n.
- 3
Print the total after the loop finishes.
Walk through Sum of First N Natural Numbers
n = 3
- 1.sum = 0 before the loop.
- 2.i = 1 gives sum = 1; i = 2 gives sum = 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum