Python program to print Fibonacci sequence

Hello everyone, welcome to programminginpython.com. Here I am going to discuss a python program which 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.

Fibonacci sequence - programminginpython.com
Fibonacci sequence – programminginpython.com

Here I use recurssion  to call the function repeatedly, so I can print the whole Fibonacci sequence.

Program on Github

Fibonacci sequence – Code Visualization

Task :

To print Fibonacci sequence for a given input.

Approach :

  • Read input number for which the Fibonacci sequence is to be found using input() or raw_input().
  • 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 fibonacci function with it next 2 numbers (n-1, n-2)
  • Print the result from Fibonacci function, which prints the required Fibonacci sequence.

Program on Github

Program :

Output :

Fibonacci sequence - programminginpython.com
Fibonacci sequence – programminginpython.com
Fibonacci sequence - programminginpython.com
Fibonacci sequence – programminginpython.com

Program on Github

Please feel free to have a look at some other math related programs here.

Leave a Reply