In this post we’ll see how to write a Python program to display Fibonacci series.
Fibonacci series is a series of natural numbers where next number is equivalent to the sum of previous two numbers. Equation for the same can be written as follows-
fn = fn-1 + fn-2
The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, and each subsequent number is the sum of the previous two numbers. Python programs in this post we'll display the Fibonacci series as- 0 1 1 2 3 5 8 ...
Python program for Fibonacci series can be written using recursion apart from writing using its iterative counterpart.
1. Fibonacci series using recursion. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of Fibonacci series program that base case is when num is 0 and 1.
def fibonacci(num): if num < 0: print('Please enter non-negative integer') # For first two numbers if num == 0: return 0 if num == 1: return 1 return fibonacci(num - 1) + fibonacci(num - 2) # running function after taking user input num = int(input('Enter how many numbers needed in Fibonacci series- ')) for i in range(num): print(fibonacci(i), end=' ')
Output
Enter how many numbers needed in Fibonacci series- 10 0 1 1 2 3 5 8 13 21 34
2. Fibonacci series program using iteration. Here for loop is used to iterate the passed number and in each iteration two previous numbers are added to get a new number in the series.
def fibonacci(num): num1 = 0 num2 = 1 series = 0 for i in range(num): print(series, end=' '); num1 = num2; num2 = series; series = num1 + num2; # running function after takking user input num = int(input('Enter how many numbers needed in Fibonacci series- ')) fibonacci(num)
Output
Enter how many numbers needed in Fibonacci series- 8 0 1 1 2 3 5 8 13
That's all for this topic Python Program to Display Fibonacci Series. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Programs Page
Related Topics
You may also like-