def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib_gen = fibonacci_generator()
# Generate and print the first 10 Fibonacci numbers
for _ in range(10):
print(next(fib_gen))
This Python code defines a generator function that produces Fibonacci numbers indefinitely:
fibonacci_generator()
is defined to yield an infinite sequence of Fibonacci numbers.yield
statement produces the current value of a
and pauses the function's execution, preserving its state for the next iteration.a
and b
are updated to the next two values in the Fibonacci sequence: a
takes the value of b
, and b
takes the sum of the old a
and b
.for
loop.