A generator function is a special type of function in Python that uses the yield keyword to generate a sequence of values on demand. Unlike regular functions, which execute and return a value, generator functions can be paused and resumed on each yield statement, allowing them to produce a stream of values over time.
Here's an example of a simple generator function that generates the first n Fibonacci numbers:
def fibonacci(n): a, b = 0, 1 for i in range(n): yield a a, b = b, a + b |
In this example, the fibonacci function takes a single argument n, which specifies the number of Fibonacci numbers to generate. Inside the function, we initialize two variables a and b to 0 and 1, respectively, and then use a for loop to iterate n times. On each iteration, we use the yield keyword to produce the current value of a, and then update a and b to the next pair of Fibonacci numbers.
To use the fibonacci generator function, you can simply call it and iterate over the returned generator object using a for loop or any other iterable-consuming method:
# Generate the first 10 Fibonacci numbers using the fibonacci generatorfor num in fibonacci(10): print(num) |
|
|
Note that each time the yield keyword is encountered, the generator function is paused and the current value of a is returned. When the for loop requests the next value, the generator function resumes where it left off and continues executing until it encounters the next yield statement. This process continues until the generator function has generated all of the values or is terminated by some other means (e.g., a return statement).