Code Explanation:
1️⃣ Defining Generator Function
def gen():
Explanation
A function gen is defined.
Because it uses yield, it becomes a generator.
It does NOT execute immediately.
2️⃣ First Yield Statement
x = yield 1
Explanation
This line does two things:
Yields value 1
Pauses execution and waits for a value to assign to x
3️⃣ Second Yield Statement
yield x * 2
Explanation
After receiving value in x, it:
returns x * 2
4️⃣ Creating Generator Object
g = gen()
Explanation
Creates a generator object g.
Function has NOT started yet.
5️⃣ First Call → next(g)
print(next(g))
Explanation
Starts execution of generator.
Runs until first yield.
๐ Executes:
yield 1
Returns:
1
Pauses at:
x = yield 1
(waiting for value)
6️⃣ Second Call → g.send(5)
print(g.send(5))
Explanation
Resumes generator.
Sends value 5 into generator.
๐ So:
x = 5
Now executes:
yield x * 2 → 5 * 2 = 10
Returns:
10
๐ค Final Output
1
10

0 Comments:
Post a Comment