Hello everyone, welcome to programminginpython.com. Here I am going to discuss a python program that prints the Fibonacci sequence of a given number.
Fibonacci sequence is calculated by summing up all the numbers below that number and its next number.
Here I use
recurssion to call the function repeatedly, so I can print the whole Fibonacci sequence.
You can watch the video on YouTube here
Fibonacci sequence – Code Visualization
To print Fibonacci sequence for a given input.
- Read input number for which the Fibonacci sequence is to be found using
- Run a for loop ranging from 0 to the input number and call
fibonacci()function which returns the output of the Fibonacci sequence.
- function fibonacci()
- check if the input number is 1, if 1 then return 1
- check if the input number is 0, if 0 then return 0
- if input number n is > 1, again call
fibonaccifunction with it next 2 numbers (n-1, n-2)
- Print the result from Fibonacci function, which prints the required Fibonacci sequence.
def fibonacci(n): if n == 1: return 1 elif n == 0: return 0 else: return fibonacci(n-1) + fibonacci(n-2) number = int(input("Enter an integer: \t")) for i in range(number): print(fibonacci(i))