To build a generator function in Python, you can use the yield keyword instead of return. The yield keyword works similarly to return, in that it returns a value from the function. However, yield also saves the current state of the function, allowing you to resume execution from where you left off the next time you call the function.
Here is an example of a simple generator function that yields the numbers from 1 to 5:
def simple_generator(): yield 1 yield 2 yield 3 yield 4 yield 5 |
When you call this function, it returns a generator object. You can then iterate over the generator object using a for loop or by using the next() function to get the next value from the generator:
gen = simple_generator()for num in gen: print(num)# Output:# 1# 2# 3# 4# 5 |
Note that when you iterate over the generator using a for loop, the loop automatically handles the StopIteration exception that is raised when there are no more values to yield. If you want to get the values from the generator one at a time, you can use the next() function:
gen = simple_generator()print(next(gen)) # Output: 1print(next(gen)) # Output: 2print(next(gen)) # Output: 3print(next(gen)) # Output: 4print(next(gen)) # Output: 5print(next(gen)) # Raises StopIteration exception |
This generator function is a simple example, but you can use the yield keyword to build more complex generators that can generate values based on input parameters, read data from files or databases, or perform other operations that generate values on the fly.