Home » Python program to print Fibonacci sequence

Python program to print Fibonacci sequence

Python program to print Fibonacci sequence

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.

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.

You can watch the video on YouTube here

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 :

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))

 

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.

Online Python Compiler

Leave a Reply

Your email address will not be published. Required fields are marked *