Write A Python Script To Generate Fibonacci Terms Using Generator Function

This article let's learn a Python program that prints the items using a python generator function.  Python generator function That will return the iterator using yield keyword.

Let's define a function and instead of using the return keyword we will be using the yield keyword to return the Fibonacci terms.

 

Write A Python Script To Generate Fibonacci Terms Using Generator Function

 

 

Write A Python Script To Generate Fibonacci Terms Using Generator Function

Take a function named fibonacci() and pass an input argument an integer number to it,  take two variables A and B and initialize it to 0 and 1. Use the for loop to iterate until the integer number  and return the value of a using the yield function.  Now swap the values of a and b, value of a becomes b and b value becomes a + b.

def fibonacci(number):
   a, b = 0, 1
   for _ in range(number):
       yield a
       a, b = b, a+b





In the main program take a variable named as  terms and ask a user to enter the number of Fibonacci Terms using input function call and convert it into an integer.  take another variable named as generator and call the Fibonacci function by passing the number of terms  as an input to the Python function.


Use of for loop to iterate upto n terms of Fibonacci series and then print the next values of the generator.  generator is a type of iterator that will return the next values of Fibonacci terms,  and keep printing the Fibonacci terms by using the for loop.

terms = int(input('Enter Number of Fibonacci Terms : '))
generator = fibonacci(terms)
for _ in range(terms):
   print(next(generator), end=" ")





Python Code
===========================

def fibonacci(number):
   a, b = 0, 1
   for _ in range(number):
       yield a
       a, b = b, a+b


terms = int(input('Enter Number of Fibonacci Terms : '))
generator = fibonacci(terms)
for _ in range(terms):
   print(next(generator), end=" ")

 





Output
============
Enter Number of Fibonacci Terms : 15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377


 
 
 
Output
===============
Enter Number of Fibonacci Terms : 34
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578

 



Conclusion
=================
Execute the above Python program by passing an integer as an input to it to note down the results.  

Comment it down  below if you have any suggestions to improve/  optimize the above Python program.

Post a Comment

0 Comments