How to Print Python Fibonacci series

Published on Aug. 22, 2023, 12:16 p.m.

To print the Fibonacci series in Python, you can use a loop or recursion. Here is an example program that uses a loop to print the Fibonacci series up to a specified number of terms:

nterms = int(input("How many terms do you want to print? "))

n1, n2 = 0, 1
count = 0

if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence up to", nterms, ":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       n1 = n2
       n2 = nth
       count += 1

In this program, we prompt the user to input the number of terms they want to print using the input() function and convert the input to an integer using the int() function. Then, we initialize the first two terms of the series to 0 and 1, respectively. We also initialize a count variable to 0 to keep track of the number of terms we have printed. If the number of terms is 1 or less, we print the corresponding term. Otherwise, we use a while loop to print each term of the series up to the specified number of terms. In each iteration of the loop, we print the current term n1, compute the next term nth as the sum of n1 and n2, update n1 to n2, n2 to nth, and increase the count by 1.

You can also use recursion to generate the Fibonacci series:

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return(fibonacci(n-1) + fibonacci(n-2))

nterms = int(input("How many terms do you want to print? "))

if nterms <= 0:
    print("Please enter a positive integer")
else:
    print("Fibonacci sequence:")
    for i in range(nterms):
        print(fibonacci(i))

In this example, we define a recursive function fibonacci(n) that takes an integer n as input and returns the nth term of the Fibonacci series. If n is less than or equal to 1, we return n. Otherwise, we

Tags:

related content