fibonacci series in python

Here is an example of a code for generating the Fibonacci series in Python:


Python


def fibonacci_series(n):

    if n <= 0:

        return []

    elif n == 1:

        return [0]

    elif n == 2:

        return [0, 1]

    else:

        fib_list = [0, 1]

        for i in range(2, n):

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

        return fib_list


n = int(input("Enter the number of terms for Fibonacci series: "))

print(fibonacci_series(n))



The function fibonacci_series(n) takes in an integer n as input and returns a list of the first n terms of the Fibonacci series. The function first checks if the input is less than or equal to 0, in which case it returns an empty list. If the input is 1, it returns a list with a single element of 0.

If the input is 2, it returns a list with 2 elements, 0 and 1. If the input is greater than 2, it creates a list fib_list and initializes it with the first two elements of the series (0 and 1). Then it uses a for loop to iterate from the 3rd element to the nth element and for each element, the value is calculated by adding the last two elements of the fib_list and append it to the list .


You can also use recursion to generate the Fibonacci series in python, which is also an efficient way of solving this problem.

Comments

Popular posts from this blog

python code for calculator

prime number program in python