Python Program to Print the Fibonacci Series Using Recursion
Beginner · Recursion
The Fibonacci series starts with 0 and 1, and each next term is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13 and so on. That rule is recursive, because term n is defined using terms n - 1 and n - 2, so it turns straight into a function that calls itself. This program prints the first 10 terms with a recursive function.
Program
First 10 terms of the Fibonacci series: 0 1 1 2 3 5 8 13 21 34
How it works
- A recursive function calls itself, and it needs a base case, where it can answer straight away, and a recursive step, which moves closer to the base case on every call.
- The base cases are
n == 0andn == 1, the two starting terms 0 and 1, and without them the function would call itself forever. - The recursive step returns
fibonacci(n - 1) + fibonacci(n - 2), which is exactly the rule of the series. fibonacci(4)asks forfibonacci(3)andfibonacci(2), which ask for smaller terms in turn, until every call reaches a base case and the answers add up to 3.- This is easy to read but slow for big n, because the same terms are worked out again and again:
fibonacci(20)alone makes 21,891 calls.
Other ways to write it
Remembering answers with lru_cache
Term 10: 55 Term 50: 12586269025 Term 100: 354224848179261915075
lru_cache stores the result of every call, so each term is worked out only once, and the same recursive function becomes fast enough for the 100th term.
Building the whole series recursively
First 10 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
This version returns the series as a list, and each call builds on the list for one term fewer, so it makes only n calls instead of thousands.
Try it yourself
Add a counter that goes up by 1 each time fibonacci() is called, and print how many calls fibonacci(15) makes.
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