Show how yield suspends a Python function and hands a value back to the caller.
yield produces one value and pauses the function there, keeping its state so it can be resumed.
def countdown(start):
while start > 0:
yield start
start -= 1
gen = countdown(3)
print(next(gen)) # 3
print(next(gen)) # 2
print(next(gen)) # 1
try:
next(gen)
except StopIteration:
print("the generator is exhausted")The first call to next runs the function until the yield, produces 3 and suspends the function there. The second call resumes from that point — start still holds 3 — decrements it and yields 2. The state of the function is preserved between calls, which is the whole point.
The final call shows how the function ends. The while loop finishes, the function returns, and Python converts that into a StopIteration, which is the signal that the generator has no more values. A for loop catches it and stops cleanly.
The difference from return is that return ends the function and gives back a single value. yield gives back a value and keeps the function alive, ready to produce the next one. A function containing yield is a generator function, and calling it returns a generator object rather than running the body.
Two advanced details worth mentioning in an interview. yield from delegates iteration to another generator, forwarding its values — simpler and faster than looping over it manually. And yield is a two-way channel: the value sent into the generator by send() becomes the result of the yield expression, which is how coroutines are built on top of plain generators.