Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Fibonacci Series Up to N

Print a number of Fibonacci terms with Python. Students handle short sequences first, update two previous terms, and separate a term count from a value limit.

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

In this one

  • Handle short sequences
  • Update a previous-term pair
  • Distinguish count from limit

How it works

  1. 1

    Handle nonpositive, one-term, and two-term cases.

  2. 2

    Otherwise print zero and one, then calculate each new sum.

  3. 3

    Shift a and b after printing c.

Edge cases

What does n = 1 print?

What does n = 1 print?

Only zero.

What does n = 0 print?

What does n = 0 print?

Invalid input; this version requires a positive term count.

What's going on

Here n is the number of terms, not the largest allowed term. The sequence begins zero, one; later terms add the previous two.

Short-input branches cover invalid counts, one term, and two terms. Otherwise the code prints the first pair, then calculates n - 2 more terms. a, b = b, c shifts the previous values together, after c has been computed.

What does n = 1 print? Only zero.

What does n = 0 print? Invalid input; this version requires a positive term count.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the next term after 0, 1, 1?

Pick an answer to check it.

Question 2

What does n = 1 print?

Pick an answer to check it.

Questions people ask

What does n = 1 print?

Only zero.

What does n = 0 print?

Invalid input; this version requires a positive term count.

What is the next term after 0, 1, 1?

2.