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 n
2n = int(input("Enter n: "))
3
4# Calculate sum
5if n <= 0:
6 sum_fib = 0
7elif n == 1:
8 sum_fib = 0
9elif n == 2:
10 sum_fib = 1
11else:
12 a, b = 0, 1
13 sum_fib = 1 # 0 + 1
14 for i in range(2, n):
15 c = a + b
16 sum_fib += c
17 a, b = b, c
18
19print(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)