Fibonacci Series Up to N

Print Fibonacci series up to n terms.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 9 of 14
fibonacci-series-up-to-n.py
1# Take n
2n = int(input("Enter number of terms: "))
3
4# Generate Fibonacci
5if n <= 0:
6 print("Invalid input")
7elif n == 1:
8 print("0")
9elif n == 2:
10 print("0 1")
11else:
12 a, b = 0, 1
13 print(a, b, end=" ")
14 for i in range(2, n):
15 c = a + b
16 print(c, end=" ")
17 a, b = b, c
18 print()

Output

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

What's going on

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