Define a function which generates Fibonacci series up to n numbers


Define a function which generates Fibonacci series up to n numbers

Note: Fibonacci numbers are numbers in integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,… ..
In mathematical terms, a sequence of Fibonacci numbers is defined by the iteration relation.
What is Fibonacci sequence and its formula?
The first two terms are 0 and 1. All other terms are derived by adding the preceding two words. This is to say that nth term is the sum of (n-1) th and (n-2) th term.

Aim: A function which generates Fibonacci series up to n numbers

Algorithm:

Step1. Start

Step2. read n

Step3. define fibo function

    def fibo(n):

Step4. read x, y

Step5. check while condition

    while n>=x:

        z=x+y

Step6. End

Program:

n=int(input(“enter the n value:”))

def fibo(n):

            x=0

             y=1

    while n>=x:

             z=x+y

             print(x)

             x=y

             y=z

fibo(n)

Ouput:

>>>

enter the n value:5

0

1

1

2

3

5

>>> 

Source Code:
Program to display the Fibonacci sequence up to n-th term
nterms = int (input (“How many terms?”))
first two terms
n1, n2 = 0, 1
count = 0
check if the number of terms is valid
if nterms <= 0:
    print (“Please enter a positive integer”)
elif nterms == 1:
    print (“Fibonacci sequence upto”, nterms, “:”)
    print (n1)
else:
    print (“Fibonacci sequence:”)
    while count <nterms:
        print (n1)
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count + = 1
Output:
How many terms? 7 Fibonacci sequence: 0 1 1 2 3 5 8

Recommended Posts:

Define a function which generates Fibonacci series up to n numbers

Have any Question or Comment?

Leave a Reply

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

Categories