Write a program of Fibonacci series in python - Fibonacci Series Program in python - Python Programming

 Fibonacci Series Program

Here's a Python program to generate the Fibonacci series up to a given number of terms:

Python Code:

def fibonacci(n): 

    """

    Returns a list of the first n Fibonacci numbers.

    """

    fib = [0, 1]

    for i in range(2, n):

        fib.append(fib[i-1] + fib[i-2])

    return fib

Here is the Practical of the above program in Jupyter Notebook

# Example usage

print(fibonacci(10))  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The fibonacci function takes a positive integer n as input and returns a list of the first n Fibonacci numbers. The function first initializes the list fib with the first two numbers (0 and 1). Then, it uses a loop to generate the remaining n-2 numbers by adding the previous two numbers to the list.

Alternatively, if you want to generate Fibonacci numbers one at a time rather than all at once, you can use a generator function:

Python Code:

def fibonacci():

    """

    Yields an infinite sequence of Fibonacci numbers.

    """

    a, b = 0, 1

    while True:

        yield a

        a, b = b, a + b

# Example usage

fib = fibonacci()

for i in range(10):

    print(next(fib)) 

This implementation defines a generator function fibonacci that yields an infinite sequence of Fibonacci numbers. The function uses a while loop to repeatedly yield the current number a, and then update the values of a and b to be the following two numbers in the sequence. The generator can be used with a for loop to generate a specified number of terms, or you can call next on the generator object to get each number one at a time.

Comments