Code Explanation:
1. Generator Function Definition
def gen():
✅ Explanation:
A function gen() is created.
Since it contains yield, it becomes a generator function.
⚠️ Important:
Generator functions do NOT run immediately.
They return a generator object.
๐น 2. First Print Statement
print("A")
✅ Explanation:
When execution starts, "A" will be printed first.
๐น 3. First yield
yield 1
✅ Explanation:
yield returns a value (1)
Then pauses the function
Function state is remembered
๐น 4. Second Print Statement
print("B")
✅ Explanation:
This line runs only when generator resumes after first pause.
๐น 5. Second yield
yield 2
✅ Explanation:
Returns 2
Again pauses the generator
๐น 6. Creating Generator Object
g = gen()
✅ Explanation:
gen() is called
But function body does NOT execute yet
A generator object g is created
๐น 7. First next() Call
print(next(g))
๐ What happens internally:
Generator starts execution from beginning.
Step-by-step:
Executes:
print("A")
Output:
A
Reaches:
yield 1
Returns:
1
Generator pauses here
✔️ Output so far:
A
1
๐น 8. Second next() Call
print(next(g))
๐ What happens internally:
Generator resumes from where it paused.
Step-by-step:
Executes:
print("B")
Output:
B
Reaches:
yield 2
Returns:
2
Generator pauses again
๐ฏ Final Output
A
1
B
2

0 Comments:
Post a Comment