Code Explanation:
1️⃣ Defining the Generator Function
def gen():
Explanation
A function named gen is defined.
Because it uses yield, it becomes a generator function.
Calling it does NOT run it immediately.
2️⃣ Yield Statement
yield 1
Explanation
yield pauses the function and returns a value.
It remembers its state for the next call.
First time execution → returns:
1
3️⃣ Return Statement (⚠️ Important)
return 2
Explanation
return ends the generator.
It does NOT behave like normal return in generators.
It raises a StopIteration exception.
The value 2 is stored inside that exception.
4️⃣ Creating Generator Object
g = gen()
Explanation
Creates a generator object.
Function is NOT executed yet.
5️⃣ First next() Call
print(next(g))
Explanation
Starts execution of generator.
Runs until first yield.
Returns:
1
6️⃣ Second next() Call
print(next(g))
Explanation
Continues execution after yield.
Hits return 2
Generator ends and raises:
StopIteration
⚠️ Value 2 is inside exception, not printed.
๐ค Final Output
1
Traceback (most recent call last):
StopIteration

0 Comments:
Post a Comment