Python - Find the Fibonacci Sequence

In this program, you will learn how to find the fibonacci sequence of any given number n


Fibonacci sequence 0,1,1,2,3,5,8,....etc. It is a interger sequence.
The first two numbers are 0 and 1. You can get fibonaci sequence by adding the prededing numbers the two terms. Fibonacci sequence represents for nth term is sum of (n-1)th and (n-2)th term.
Example: 6 terms # - 0 # - 1 # - 0, 1, 0+1 # - 0, 1, 1, 1+1 # - 0, 1, 1, 2, 1+2 # - 0, 1, 1, 2, 3, 2+3 # - 0, 1, 1, 2, 3, 5


Program Code



    # This program to display fibonacci sequence for given n-th term


    #term = 10
    tnum = int(input('Enter how many terms want to display: '))
    
    # 0 and 1 are two terms
    n1, n2 = 0, 1
    tcount = 0
    
    if tnum <= 0: 
        print('Please enter a positive integer to display fibonacci sequence')
    
    # check the term is 1
    elif tnum == 1:
         print('Fibonacci sequence for {0} term is:'.format(tnum))
         print(n1)
    
    # Fibonacci Sequence
    else:
        print('The Fibonacci Sequence')
        while( tcount < tnum):
            print(n1)
            nextnum = n1 + n2
            #Assign previous and latest values
            n1 = n2
            n2 = nextnum
            tcount +=1 
    

Output



    Enter how many terms want to display: 9
    The Fibonacci Sequence
    0
    1
    1
    2
    3
    5
    8
    13
    21

In this program, the number of terms stored in tnum variable which is 9. You can change the value of tnum to find the fibonacci sequence for different numbers.
The first term and second term values are stored as 0 and 1 respectively. We use while loop if the number is more than 2 to find the next term in the seqence by adding the preceeding two terms. We then interchange the variables and continue on with the process.

The following topics can be useful to understand this program.



Related Tutorials