Code Explanation:
1) def gen():
Defines a generator function called gen.
A generator uses yield instead of return, allowing it to pause and resume execution.
2) Inside gen()
x = yield 1
yield x + 2
First yield 1 → when the generator is started, it will output 1.
Then, it pauses and waits to receive a value via .send().
That received value is assigned to variable x.
Finally, it yields x + 2.
3) g = gen()
Creates a generator object g.
At this point, nothing has run inside gen() yet.
4) print(next(g))
next(g) starts execution of the generator until the first yield.
At the first yield, 1 is produced.
The generator pauses, waiting for the next resume.
Output:
1
5) print(g.send(5))
send(5) resumes the generator and sends 5 into it.
That 5 is assigned to x.
Now generator executes the next line: yield x + 2 → yield 5 + 2 → yield 7.
Output:
7
Final Output
1
7
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment