Code Explanation:
1. ๐ง Define the Generator Function
def gen():
This creates a function named gen.
Because the function contains yield, it becomes a generator function.
A generator does not execute its entire body immediately.
2. ๐ Initialize x
x = 1
When the generator starts running, x is initialized to:
x = 1
3. ๐ Check the while Condition
while x < 10:
Python checks whether:
1 < 10
This is True, so the loop starts.
4. ๐ First yield
yield x
At this moment:
yield 1
The generator pauses and sends 1 to whoever called next(g).
So:
next(g)
returns:
1
Important: yield pauses the function instead of ending it.
5. ๐ Resume and Multiply
x *= 3
When the next next(g) is called, execution resumes from where it paused.
Now:
x = 1 × 3
x = 3
6. ๐ Second Loop Check
Python reaches:
while x < 10:
Now:
3 < 10
is True.
So the loop continues.
7. ๐ Second yield
yield x
Now the generator yields:
3
Therefore the second:
next(g)
returns 3.
8. ๐จ️ print() Executes
print(next(g), next(g))
Python evaluates the arguments from left to right:
First next(g) → 1
Second next(g) → 3
So the final output is:
1 3
๐ Generator Flow
gen()
↓
x = 1
↓
yield 1
↓
pause
↓
next(g)
↓
x = 3
↓
yield 3
↓
pause
๐ก Key Interview Trick
next() does not restart the generator.
It resumes execution from the previous yield point.
So the sequence produced by this generator would be:
1 → 3 → 9
The two next() calls consume only:
1 → 3
Hence:
✅ Final Answer
1 3

0 Comments:
Post a Comment