Code Explanation:
๐น 1. Generator Function Definition
def gen():
✅ Explanation:
A function named gen() is created.
Since it contains yield, it becomes a generator function.
Calling it will return a generator object.
๐น 2. First Yield Statement
x = yield 1
✅ Explanation:
This line does two things:
Yields value:
1
Pauses execution and waits for a value to be sent back.
The sent value will later be stored in:
x
๐น 3. Second Yield Statement
yield x + 5
✅ Explanation:
After receiving a value through send(),
Python calculates:
x + 5
and yields the result.
๐น 4. Creating Generator Object
g = gen()
✅ Explanation:
Generator function is called.
But code inside does NOT run immediately.
Instead:
g
stores a generator object.
Something like:
<generator object gen at 0x...>
\๐น 5. First Execution
print(next(g))
✅ Explanation:
next(g) starts the generator.
Execution enters:
x = yield 1
Generator Yields
1
and pauses.
At this point:
x
has NOT received any value yet.
Output
1
๐น 6. Sending a Value
print(g.send(10))
✅ Explanation:
send(10) resumes generator execution.
The value:
10
is sent back into:
x = yield 1
So now:
x = 10
๐น 7. Executing Next Line
Generator continues:
yield x + 5
Substitute:
yield 10 + 5
Calculation:
15
Generator yields:
15
๐น 8. Printing Result
print(g.send(10))
prints:
15
๐ฏ Final Output
1
15

0 Comments:
Post a Comment