Here's an example of how you can use a generator function:
def squares(n): for i in range(n): yield i**2# Use the squares generator to generate and print the first 5 squaresfor square in squares(5): print(square) |
In this example, we define a generator function called squares that yields the squares of the integers from 0 to n-1. The for loop inside the function iterates over the range(n) object, and on each iteration, it yields the square of the current integer. When the loop is done, the function returns, and the generator is closed.
To use the squares generator, we can call it with an argument of 5 to generate the first 5 squares. We then use a for loop to iterate over the generator object and print each square. The output of this code will be:
014916 |
Note that the squares generator function is only executed when we create a generator object by calling it. The values are generated on-the-fly as we iterate over the generator using the for loop. This makes generators memory-efficient and allows us to work with very large sequences of data that we might not be able to fit in memory all at once.