Code Explanation:
๐น 1. Function Definition
def gen():
✅ Explanation:
A function gen is defined.
Because it uses yield, it becomes a generator function (not a normal function).
๐น 2. First yield
yield 1
✅ Explanation:
yield produces a value without ending the function.
It pauses execution and remembers its state.
๐น 3. Second yield
yield 2
✅ Explanation:
When resumed, the function continues from where it stopped.
Now it yields 2.
๐น 4. Third yield
yield 3
✅ Explanation:
On next resume, it yields 3.
After this, the generator is exhausted.
๐น 5. Creating Generator Object
g = gen()
✅ Explanation:
Calling gen() does NOT execute the function immediately.
It returns a generator object.
Execution starts only when next() is called.
๐น 6. First next() Call
print(next(g))
๐ What happens:
Starts execution of gen()
Runs until first yield
✔️ Output:
1
๐น 7. Second next() Call
print(next(g))
๐ What happens:
Resumes from previous pause
Continues to second yield
✔️ Output:
2
๐ฏ Final Output
1
2

0 Comments:
Post a Comment