Code Explanation:
1. Define the generator function:
def gen():
val = yield 1
yield val * 2
This generator yields two values:
First, it yields 1.
Then, it waits for a value to be sent in, assigns it to val, and yields val * 2.
2. Create the generator object:
g = gen()
Now g is a generator object.
3. Start the generator:
print(next(g))
This starts the generator and runs it until the first yield, which is yield 1.
It outputs 1, and pauses at val = yield 1, waiting for a value to be sent into it.
Output so far:
1
4. Send a value into the generator:
print(g.send(10))
This resumes the generator and sends 10 into the paused yield expression.
So val = 10.
The next line yield val * 2 becomes yield 20.
Output:
20


0 Comments:
Post a Comment