Display the terms of a Fibonacci series
Expt. No.13
Page No.26
Fibonacci series
Aim
To write a Python program that displays the first n terms of the Fibonacci series.
Concepts used
Algorithm
- Input the number of terms n.
- Set a = 0 and b = 1.
- Repeat n times: print a, then set a, b to b, a + b.
Program
# Display the first n terms of the Fibonacci series n = int(input("How many terms? "))a = 0b = 1print("Fibonacci series:")for i in range(n): print(a, end=" ") a, b = b, a + bprint()
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python fibonacci_series.py
How many terms? 10
Fibonacci series:
0 1 1 2 3 5 8 13 21 34
✓ Printed by running this program, not typed by hand.
Result
The first 10 terms were 0 1 1 2 3 5 8 13 21 34; each term is the sum of the two before it.
Viva voce: what the examiner may ask
01What is the Fibonacci series?
A series that starts 0, 1 in which each term is the sum of the previous two.
02Why is a, b = b, a + b written on one line?
Both new values are worked out from the old a and b before either changes. Two separate lines would use the already-changed a.
03What does end=" " do?
It prints a space instead of a new line after each term, so the terms stay on one line.
Variations for the lab test
- Print only the even terms among the first 20.
- Print the terms that are less than 500.
- Find the sum of the first n terms.
! Common mistake Writing
a = b and then b = a + b on separate lines: b becomes 2 × the old b and the series goes wrong after the third term.