Code Explanation:
๐น 1. Defining a Generator Function
def gen():
✅ Explanation:
A function named gen is created.
Since it contains the yield keyword, it becomes a generator function.
A generator does not execute immediately when it is defined.
Current state:
Generator function created.
๐น 2. Starting the for Loop
for i in range(3):
✅ Explanation:
range(3) generates numbers from 0 to 2.
Values of i will be:
0
1
2
Visual:
Iteration 1 → i = 0
Iteration 2 → i = 1
Iteration 3 → i = 2
๐น 3. Using yield
yield i * 2
✅ Explanation:
yield returns a value and pauses the function.
Unlike return, the function does not end.
It remembers its current state and continues from the same place when next() is called again.
Formula:
Yield Value = i × 2
๐น 4. Creating the Generator Object
g = gen()
✅ Explanation:
Calling gen() does not execute the function.
Instead, it creates a generator object.
Current state:
g
↓
<generator object>
The loop has not started yet.
๐น 5. First next() Call
print(next(g))
✅ Explanation:
next(g) starts executing the generator.
Current value:
i = 0
Calculation:
0 * 2
Result:
0
yield returns:
0
The generator pauses here.
Output:
0
๐น 6. Generator Pauses
After returning 0, the generator does not restart.
It pauses at:
yield i * 2
Current position:
Waiting for next() call
๐น 7. Second next() Call
print(next(g))
✅ Explanation:
The generator resumes from where it stopped.
Loop continues with:
i = 1
Calculation:
1 * 2
Result:
2
yield returns:
2
Generator pauses again.
Output:
2
๐น 8. Current Generator State
The generator has processed:
i = 0 ✅
i = 1 ✅
Still remaining:
i = 2
If we call:
print(next(g))
Output:
4
because:
2 * 2 = 4
๐ฏ Final Output
0
2

0 Comments:
Post a Comment