Fibonacci Generator

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))

Fibonacci Generator Explained

This Python code defines a generator function that produces Fibonacci numbers indefinitely:

  1. Function Definition: The function fibonacci_generator() is defined to yield an infinite sequence of Fibonacci numbers.
  2. Yield Statement: The yield statement produces the current value of a and pauses the function's execution, preserving its state for the next iteration.
  3. Updating Values: After yielding, 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.
  4. Example Usage: The generator is used to print the first 10 Fibonacci numbers by iterating over it with a for loop.