Sum of First N Fibonacci Terms
Calculate sum of first n Fibonacci terms.
IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 10 of 14
sum-of-first-n-fibonacci-terms.py
1# Take n2n = int(input("Enter n: "))34# Calculate sum5if n <= 0:6 sum_fib = 07elif n == 1:8 sum_fib = 09elif n == 2:10 sum_fib = 111else:12 a, b = 0, 113 sum_fib = 1 # 0 + 114 for i in range(2, n):15 c = a + b16 sum_fib += c17 a, b = b, c1819print(f"Sum of first {n} Fibonacci terms: {sum_fib}")
Output
Enter n: 5 Sum of first 5 Fibonacci terms: 7
What's going on
Generate Fibonacci terms and accumulate sum.
Key Concepts:
Generate Fibonacci sequence
Add each term to sum
Handle edge cases (n <= 2)
🔗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