Code Explanation:
1. Defining the Generator Function
def process():
- Defines a generator function named process().
- A generator function uses the yield keyword to produce values one at a time.
- It remembers its execution state between function calls.
2. Yielding the First Value
x = yield 10
- The function pauses and produces the value 10.
- Execution stops temporarily at the yield statement.
- When a value is sent using send(), that value is assigned to variable x.
3. Yielding the Second Value
y = yield x + 5
- Calculates x + 5.
- Produces the calculated value and pauses again.
- The next value sent using send() is assigned to variable y.
4. Yielding the Final Value
yield y * 2
- Multiplies the value of y by 2.
- Produces the final result.
- The generator pauses after yielding this value.
5. Creating the Generator Object
g = process()
- Calls the generator function.
- Creates a generator object and stores it in g.
- The function body does not execute immediately.
- Execution begins when next() or send() is called.
6. Executing the First Generator Step
print(next(g))
- Starts the generator execution.
- The first yield produces 10.
- The generator pauses at x = yield 10.
- Output is 10.
7. Sending a Value into the Generator
print(g.send(20))
- Sends 20 into the paused generator.
- The value 20 is assigned to x.
- Python calculates x + 5, which is 25.
- The second yield produces 25.
- The generator pauses again.
8. Sending Another Value into the Generator
print(g.send(7))
- Sends 7 into the paused generator.
- The value 7 is assigned to y.
- Python calculates y * 2, which is 14.
- The final yield produces 14.
Understanding Generator Execution
Operation Value sent Output
next(g) — 10
g.send(20) 20 25
g.send(7) 7 14
Final Output
Correct Output
10 25 14


0 Comments:
Post a Comment