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 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
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)
🔗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