Join my course at Udemy (Python Programming Bible-From beginner to advanced )

Blogger templates

Sunday 16 August 2020

Difference between generator and function in python.

 Any python function that has ‘yield’ inside the function is a generator function. A normal function in python uses ‘return’ to return a value from the function.

There are three properties in generator function

  • Function uses ‘yield’ to return from function.
  • Function caller uses ‘next’ function to traverse the function.
  • And when end of the function is reached then “StopIteration” exception is called automatically by python.  

Following screenshot shows a generator function. In the following function there are two ‘yield’ to return two value from the function.

During function execution, whenever function encounters the YIELD, it returns the value and function goes to sleep with all context information.

The function wakes up when caller calls the function using ‘next’ function and the function starts execution till it encounters the next ‘yield’ and if no ‘yield’ is encountered and it reaches the end of the function and ‘StopIteration’ exception is raised by function.

In the following screenshot, i have called ‘next’ function two times and so first ‘10’ is returned and then ’20′ is returned.

As there are two yield in the function, the two ‘next’ command will work fine. The third call of ‘next’ function will raise ‘StopIteration’ exception as shown in the below screen shot.

Share:

0 comments:

Post a Comment

Feature Top (Full Width)

Pageviews

Search This Blog