How does a function containing `yield` behave differently from a normal function?
Answer
Any function whose body contains at least one `yield` statement becomes a generator function: calling it does not run the body at all, it immediately returns a generator object that implements the iterator protocol for you automatically. Each call to `next()` on that generator runs the function body until the next `yield` expression, pauses execution there, and returns the yielded value; the function's entire local state — variables, the instruction pointer, even open loops — is preserved between calls, and execution resumes exactly where it left off on the following `next()`.
Strong answer includes
- presence of yield makes it a generator function
- calling it returns a generator object without running the body
- execution pauses at yield and resumes with full local state preserved
Practical example
Run the code to see the result.
Calling countdown creates the generator without running its body. Each consumption resumes execution until the next yield and preserves n between resumptions.
Expected result: created, started, 3, 2, then [1].