Fibonacci Series Up to N

Print Fibonacci series up to n terms.

Logic BuildingIntermediate
Logic Building
# Take n
n = int(input("Enter number of terms: "))

# Generate Fibonacci
if n <= 0:
    print("Invalid input")
elif n == 1:
    print("0")
elif n == 2:
    print("0 1")
else:
    a, b = 0, 1
    print(a, b, end=" ")
    for i in range(2, n):
        c = a + b
        print(c, end=" ")
        a, b = b, c
    print()

Output

Enter number of terms: 8
0 1 1 2 3 5 8 13

Each term is sum of previous two.

Key Concepts:

  • Start with 0 and 1
  • Each next term = previous + previous-1
  • Use two variables to track last two terms