Code Explanation:
Line 1: Define the Generator
def gen():
Defines a generator function. Its execution begins when we call next() on the generator object.
Line 2: Yield a Value
x = yield 5
The generator sends 5 to the caller and pauses. The assignment to x waits until the generator resumes.
Line 3: Yield the Calculation
yield x + 2
After resuming, Python calculates x + 2 and yields the result.
Line 4: Create the Generator
g = gen()
Creates a generator object. The function body has not executed yet.
Line 5: Get the First Value
a = next(g)
The generator starts and pauses at yield 5.
Therefore:
a = 5
Line 6: Send a Value into the Generator
b = g.send(10)
The value 10 becomes the result of the paused yield expression.
Therefore:
x = 10
b = 10 + 2 = 12
Line 7: Print the Sum
print(a + b)
Now:
a + b = 5 + 12
= 17
4. Execution Table
Step Operation Value
1 next(g) a = 5
2 g.send(10) x = 10
3 yield x + 2 b = 12
4 print(a + b) 17
5. Key Interview Concept
- yield 5 sends 5 out of the generator.
- g.send(10) sends 10 into the paused generator.
- The generator resumes from where it paused; it does not restart.
Final output:
17


0 Comments:
Post a Comment