Code Explanation:
๐น 1. Generator Function Definition
def gen():
✅ Explanation:
A generator function gen() is created.
Since it uses yield, it becomes a generator.
๐น 2. Receiving Value with yield
x = yield
✅ Explanation:
This is a special use of yield.
๐ What it does:
Pauses generator execution
Waits to RECEIVE a value using:
send(value)
The received value gets stored in:
x
๐น 3. Second yield
yield x * 2
✅ Explanation:
Multiplies received value by 2
Returns result using yield
๐น 4. Creating Generator Object
g = gen()
✅ Explanation:
Calling gen() does NOT run function immediately.
It creates a generator object g.
๐น 5. Starting Generator
next(g)
✅ Explanation:
Before using:
send(value)
generator must first reach the first yield.
๐ What happens internally:
Execution starts:
x = yield
Generator pauses here waiting for value.
⚠️ Important:
At this moment:
x → not assigned yet
Generator is now ready to receive data.
๐น 6. Sending Value into Generator
g.send(5)
✅ Explanation:
Sends value 5 into paused generator.
That value becomes:
x = 5
๐น 7. Execution Resumes
After receiving value:
yield x * 2
Calculation:
5 * 2 = 10
Generator yields:
10
๐น 8. Printing Result
print(g.send(5))
✅ Output:
10
๐ฏ Final Output
10

0 Comments:
Post a Comment