Python Program to Print the Fibonacci Series
Beginner · Numbers · CBSE class 11 practical list · CBSE class 12 practical list
The Fibonacci series starts with 0 and 1, and each next term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13 and so on. This program prints the first n terms of the series.
Program
First 10 terms of the Fibonacci series: 0 1 1 2 3 5 8 13 21 34
How it works
aandbhold the two most recent terms, starting at 0 and 1.- Each pass of the loop prints
a, then works out the next term asa + b. - The terms then move along by one:
atakes the value ofb, andbtakes the new term. end=" "prints the terms on one line, and the finalprint()ends that line.
Other ways to write it
Using recursion
Fibonacci series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
A recursive function matches the definition closely, but it repeats a lot of work and gets slow beyond about 30 terms.
Terms up to a limit
Fibonacci numbers up to 100: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
A while loop suits a limit on the value rather than a count of terms, and a, b = b, a + b updates both terms at once.
Try it yourself
Change the program to print only the even terms among the first 20.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises