Generators and yield

A function that contains yield is a generator function. Calling it doesn't run the body. It returns a generator, which is an iterator.

Each next() runs the body until the next yield, hands out that value, and pauses right there, with all local variables kept. The next next() resumes from the same spot. When the function returns, the generator raises StopIteration, and a for loop ends.

The program prints inside countdown so you can watch it pause and resume.

Generators are the easiest way to write your own iterator: no class, no __next__, just a loop with yield. They also produce values lazily, one at a time, so they can handle a huge file or an endless stream in constant memory. Interviewers ask "what is the difference between return and yield?" This page is the answer.

Run it, then call next(gen) once more after the loop.