Sobes.tech
Junior — Middle

What result will be obtained when a generator function in Python completes execution?

sobes.tech AI

Answer from AI

When a generator function in Python completes execution, a StopIteration exception is raised. This signals that the generator has exhausted all its values and can no longer produce new ones.

If you iterate over a generator in a for loop, this exception is handled automatically, and the loop ends.

Example:

def gen():
    yield 1
    yield 2

g = gen()
print(next(g))  # Outputs 1
print(next(g))  # Outputs 2
print(next(g))  # Raises StopIteration

Thus, StopIteration is the standard way to indicate that a generator has finished.

What result will be obtained when a generator… - sobes.tech